Pull to refresh

Kotlin: SetUp SharedFlow

Level of difficultyHard

KotlinCoroutines: set up SharedFlow by testing ⚒

Photo by Daniil Silantev on Unsplash
Photo by Daniil Silantev on Unsplash

Source: 

  1. Initialize MutableSharedFlow:

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

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

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

Result — the collection is not triggered.

  1. 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 }.

  1. Emit multiply values:

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

Result — { flow = 1}.

  1. 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 }.

  1. 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 💚.

Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.