Kotlin: SetUp SharedFlow ⚒

KotlinCoroutines: set up SharedFlow by testing ⚒

Vladislav Shesternin
2 min readOct 21, 2021

Source: https://github.com/Kotlin/kotlinx.coroutines/issues/2034

  1. Initialize MutableSharedFlow:
val flow = MutableSharedFlow<Int>()

2. Collect MutableSharedFlow:

init {
CoroutineScope(Dispatchers.Default).launch {
flow.collect { log("flow = $it") }
}
}

3. Emit value:

val value: Int = 5
flow.tryEmit(value)

Result — the collection is not triggered.

4. Let’s make the collection collect:

val flow = MutableSharedFlow<Int>(replay = 1)

replay — how many items are replayed to new subscribers (optional, defaults to zero);

Result{ flow = 5 }.

5. Emit multiply values:

listOf(1, 2, 3).onEach { value -> flow.tryEmit(value) }

Result{ flow = 1}.

6. Let’s make the collection collect multiply:

val flow = MutableSharedFlow<Int>(replay = 3)

OR

val flow = MutableSharedFlow<Int>(replay = 1, extraBufferCapacity = 2)

extraBufferCapacity — how many items are buffered in addition to replay so that emit does not suspend while there is a buffer remaining (optional, defaults to zero);

Result{ flow = 1, flow = 2, flow = 3 }.

7. Collect only the last value as StateFlow:

val flow = MutableSharedFlow<Int>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)

onBufferOverflow — configures an action on buffer overflow (optional, defaults to suspending emit call, supported only when replay > 0 or extraBufferCapacity > 0);

SUSPEND — waits until the buffer is free.

DROP_LATEST — removes new values, leaving old ones.

DROP_OLDEST — removes old values, leaving new ones.

Result{ flow = 3 }.

PS. Vel_daN: Love what You DO 💚.

--

--