Erik
08/04/2020, 10:04 AMMutableStateFlow.value
read-and-write operation? I mean: first read the current value
(this is thread-unsafe, because I don't know if another thread will change the value just after I read it), then use it to set it again. I can probably use a Channel
for this, but how do I do this? And there are probably alternatives?Horv
08/04/2020, 10:31 AMAis often a good way to insert events into a flow. It provides a concurrency primitive (or low-level tool) for passing values between several coroutines.ConflatedBroadcastChannel
By conflating the events, we keep track of only the most recent event. This is often the correct thing to do, since UI events may come in faster than processing, and we usually don't care about intermediate values.
If you do need to pass all events between coroutines and don't want conflation, consider using awhich offers the semantics of aChannel
using suspend functions. TheBlockingQueue
builder can be used to make channel backed flows.channelFlow
Horv
08/04/2020, 10:33 AMErik
08/04/2020, 3:32 PMprivate val mutex = Mutex()
to lock access to my mutable state flow's read-write operation, more or less like so:
class Foo {
private val mutex = Mutex()
private val flo = MutableStateFlow<Bar?>(null)
suspend fun baz() = mutex.withLock {
val bar = flo.value
val newBar = qux(bar)
flo.value = newBar
}
}
Erik
08/04/2020, 3:36 PMMutex
, I think that a private CoroutineContext
based on a single thread (e.g. Executors.newSingleThreadExecutor().asCoroutineDispatcher()
) would also work, when used in withContext(coroutineContext)
wrapping the read-write operation. The downside is that the context uses resource that one must close()
, but there can be a performance gain depending on the number of callers of baz()
.Zach Klippenstein (he/him) [MOD]
08/04/2020, 4:39 PMErik
08/04/2020, 4:40 PMZach Klippenstein (he/him) [MOD]
08/04/2020, 4:42 PMErik
08/04/2020, 4:43 PMErik
08/04/2020, 4:45 PMErik
08/04/2020, 4:46 PMErik
08/04/2020, 6:28 PM