natario1
02/08/2021, 2:23 PMclass 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 workaroundspand
02/08/2021, 2:33 PMnatario1
02/08/2021, 2:35 PMValtteri Puonti
02/08/2021, 2:42 PMprivate 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!natario1
02/08/2021, 2:49 PMconnectionJob
variable anywayuli
02/09/2021, 2:10 PMObsoleteCoroutinesApi
but I would say fine until a replacement is ready.Rechee Jozil
02/15/2021, 2:23 AM