https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

natario1

02/08/2021, 2:23 PM
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

spand

02/08/2021, 2:33 PM
n

natario1

02/08/2021, 2:35 PM
Yes - I didn't know about it 😄 looks like it can help, thank you!
👍 1
v

Valtteri Puonti

02/08/2021, 2:42 PM
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

natario1

02/08/2021, 2:49 PM
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

uli

02/09/2021, 2:10 PM
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

Rechee Jozil

02/15/2021, 2:23 AM
Nothing wrong with the java primitives. But yea I'd check out mutex like someone suggested above
4 Views