masteramyx
01/27/2024, 8:46 PMjob
checking its value could be looking at an old value and not most recent value changed by another thread and take an incorrect code path.
We can set the field as `@Volatile`to ensure atomic read/writes and visiblity to other threads.
But could this concern also be resolved by sharing a coroutine context between the 2 jobs? I think by default launch
uses Dispatchers.DEFAULT
. Would passing in a defined coroutinecontext to the launch
block ensure the dispatcher shares a thread for those 2 coroutines?masteramyx
01/27/2024, 8:51 PMclass Engine(val scope: CoroutineScope) {
@Volatile private var msgReceived = false
val job: Job? = null
init {
scope.launch {
flow
.onEach {
msgReceived = true
job?.cancel()
job = null
}
.launchIn(this)
}
}
fun anotherMethod() {
job =
scope.launch {
delay(DELAY)
if (!msgReceived) {
flow.emit(Error())
}
}
}
}
Could @Volatile
be replaced with a custom context passed into the 2 launch()
s?streetsofboston
01/27/2024, 9:41 PMvide
01/28/2024, 10:54 AMDispatchers.Default.limitedParallelism(1)
coroutines launched to this dispatcher will be ran on at most 1 thread at a time, but the thread can changeZach Klippenstein (he/him) [MOD]
01/28/2024, 7:31 PMmasteramyx
01/30/2024, 7:57 PMZach Klippenstein (he/him) [MOD]
01/30/2024, 8:18 PM