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

Daniele Segato

06/30/2021, 10:59 PM
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

Dominaezzz

07/01/2021, 7:43 AM
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

Daniele Segato

07/01/2021, 7:44 AM
I've updated my question
d

Dominaezzz

07/01/2021, 7:52 AM
Oh, I'm pretty sure there's a behaviour difference there. (State flow is still better)
d

Daniele Segato

07/01/2021, 7:52 AM
I'm trying to understand when I should use a
MutableSharedFlow
and why :)
n

Nick Allen

07/03/2021, 7:11 PM
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

Daniele Segato

07/03/2021, 7:45 PM
Thanks @Nick Allen very clear.
3 Views