kotlin-interview-tip
Mohamad Abuzaid 1 year ago
mohamad-abuzaid #kotlin-tips

In Kotlin Coroutines...

What is the difference between Flow, StateFlow and SharedFlow?

-------------------------

[1] Flow


Flow is a cold asynchronous stream of values that can be collected by a collector. Flow is similar to the concept of an Iterator in synchronous programming.

Cold Stream: which means that it will start emitting values only when a collector starts collecting them. Once a collector stops collecting, the flow stops emitting values.

fun intFlow(): Flow<Int> = flow {
    for (i in 1..5) {
        emit(i)
    }
}

fun main() {
    intFlow().collect {
        println(it)
    }
}


----------------------------

[2] StateFlow


A special kind of flow in Kotlin Coroutines that represents a state that can be observed and updated by multiple collectors.

Hot Stream: which means that it will start emitting values as soon as it is created and it will continue to emit new values even when there are no collectors.

  • When a new collector is added later on: State Flow will emit the current value and it will emit new values every time the value changes.
val count = StateFlow(0)

fun main() = runBlocking {
    launch {
        count.collect { value ->
            println("Count value: $value")
        }
    }

    for (i in 1..5) {
        count.value = i
    }
}


----------------------------

[3] SharedFlow


Allows multiple collectors to share a single source of values, similar to a broadcast channel.

Hot Stream: which means that it will start emitting values as soon as it is created and it will continue to emit new values even when there are no collectors.

  • Unlike "State Flow", "𝐒𝐡𝐚𝐫𝐞𝐝 𝐅𝐥𝐨𝐰" emits values only once and it uses a buffer to store the values. So if a new collector is added later on, it will not get the current value. Instead, it will have to read the previous values from the buffer.
val sharedFlow = SharedFlow<Int>(extraBufferCapacity = 100)

fun main() = runBlocking {
    launch {
        sharedFlow
            .buffer()
            .collect { value ->
                println("Collected value: $value")
            }
    }

    for (i in 1..5) {
        sharedFlow.emit(i)
    }
}
1
532
Effective UI/UX Design in Android Apps (2/3)

Effective UI/UX Design in Android Apps (2/3)

1675112374.jpg
Mohamad Abuzaid
7 months ago
Kotlin Coroutines (1/3)

Kotlin Coroutines (1/3)

1675112374.jpg
Mohamad Abuzaid
1 year ago
Kotlin's Interoperability with Java (3/3)

Kotlin's Interoperability with Java (3/3)

1675112374.jpg
Mohamad Abuzaid
7 months ago
SOLID principles explained

SOLID principles explained

1675112374.jpg
Mohamad Abuzaid
1 year ago
Jetpack Compose Animation

Jetpack Compose Animation

1675112374.jpg
Mohamad Abuzaid
3 months ago