Given this class ```class Client { private su...
# coroutines
n
Given this class
Copy code
class Client {

    private suspend fun connectInternal(url: String) { /* does connection stuff */ }
    private suspend fun disconnectInternal() { /* does disconnection stuff */ }

    suspend fun connect(url: String) {
        TODO("Should call connectInternal")
    }

    suspend fun disconnect() {
        TODO("Should call disconnectInternal")
    }
}
I'd like to implement
connect
and
disconnect
so that they call the internal APIs in a thread-safe fashion. Client can only be connected to one url at a time so, for example: • disconnect should cancel any in-progress connection • when connect is called from multiple threads, only the last succeeds, the others will be canceled I can implement this in a thousand ways, but I always end up using some Java threading primitive at least in 1 place (like a synchronized block or a lock). Is there a way to achieve the same only with coroutine primitives? One simple option is do everything in like a
newSingleThreadContext
but that's more of a bad workaround
s
n
Yes - I didn't know about it 😄 looks like it can help, thank you!
👍 1
v
you might also keep a
private var connectionJob: Job? = null
in memory and cancel the job on new connections and disconnects? edit: just realised the question is more about thread-safety, sry!
n
Yes, I have tried something similar with Job.cancel() and Job.join() but I had to synchronize access to the
connectionJob
variable anyway
👍🏼 1
u
how about actors? https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/actor.html
ObsoleteCoroutinesApi
but I would say fine until a replacement is ready.
Alternative you could send comands(seald classes) through state flow and handle connect and disconnect in the collector. You could also use conflate as the last command fully determines the next desired state
👍 1
r
Nothing wrong with the java primitives. But yea I'd check out mutex like someone suggested above