connect

inline suspend fun <T : RpcService, R : RpcService, S> SingleChannelConnection<S>.connect(crossinline host: suspend (R) -> T)

Connects both default channels for a connection (incoming and outgoing).

Provides the host lambda with a stub connected to the default outgoing channel for the connection, and then connects the returned service as the hosted channel for the connection.

This is equivalent to calling registerDefault for T instance and using defaultChannel and toStub to create R.

Samples

import com.monkopedia.ksrpc.RpcService
import com.monkopedia.ksrpc.annotation.KsMethod
import com.monkopedia.ksrpc.annotation.KsService
import com.monkopedia.ksrpc.channels.connect
import com.monkopedia.ksrpc.ksrpcEnvironment
import com.monkopedia.ksrpc.serialized
import com.monkopedia.ksrpc.sockets.asConnection
import com.monkopedia.ksrpc.toStub
import io.ktor.utils.io.ByteChannel

fun main() { 
   //sampleStart 
   val env = ksrpcEnvironment { }

val readChannel = ByteChannel(autoFlush = true)
val writeChannel = ByteChannel(autoFlush = true)
val connection = (readChannel to writeChannel).asConnection(env)

// connect<Host, Client> wires both directions in one call:
// - It gets the remote's default channel as a Client stub
// - The lambda returns the Host implementation to register locally
connection.connect<ServerApi, ClientApi, String> { clientStub ->
    // clientStub is a typed proxy for the remote's ClientApi.
    // Return the local ServerApi implementation to host.
    object : ServerApi {
        override suspend fun fetchData(key: String): String {
            // Can call back to the client within the handler.
            clientStub.onUpdate("fetching $key")
            return "value-for-$key"
        }
    }
} 
   //sampleEnd
}

@JvmName(name = "connectSerialized")
suspend fun <T> SingleChannelConnection<T>.connect(host: suspend (SerializedService<T>) -> SerializedService<T>)

Raw version of connect, performing the same functionality with SerializedService directly.