Is there any performance or concurrency difference...
# coroutines
d
Is there any performance or concurrency difference in using a MutableSharedFlow (with replay 1, buffer 1 and drop oldest) over a MutableStateFlow?
Copy code
MutableSharedFlow<Something?>(
    replay = 1,
    extraBufferCapacity = 1,
    onBufferOverflow = BufferOverflow.DROP_OLDEST
)
vs
Copy code
MutableStateFlow<Something?>(null)
d
If you mean, buffer 0, then state flow might perform ever so slightly better but I don't think it's significant enough to let that dictate your decision.
d
I've updated my question
d
Oh, I'm pretty sure there's a behaviour difference there. (State flow is still better)
d
I'm trying to understand when I should use a
MutableSharedFlow
and why :)
n
To clarify:
MutableSharedFlow
maintains a buffer of size
replay + extraBufferCapacity
(it's "extra" for a reason".
MutableStateFlow
has additional behavior in that it discards duplicates. A
MutableStateFlow
is equivalent to
MutableSharedFlow(replay = 1, extraBufferCapacity = 0, onBufferOverflow = BufferOverflow.DROP_OLDEST)
, where you always read from the shared flow with
sharedFlow.distinctUntilChanged()
.
While
MutableStateFlow
is good for managing state that can change,
MutableSharedFlow
is better suited for broadcasting event objects, where collectors are essentially event listeners. If something happens twice, you don't necessarily want the second event to be thrown away. The "event" in this case could be a sealed class of different event types, or could just be Unit to act as a simple signal.
d
Thanks @Nick Allen very clear.