WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Advanced · question 49 of 100

Explain the difference between sharedFlow and stateFlow in Kotlin’s coroutines library. When should you use each?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

‘sharedFlow‘ and ‘stateFlow‘ are both classes in Kotlin’s coroutines library that allow for the emission of asynchronous streams of data. However, they differ in a few important ways, and are suited to different kinds of use cases.

**StateFlow**

‘StateFlow‘ is a type of ‘Flow‘ that represents a single, immutable state value that can be observed by multiple collectors. In other words, it is a broadcast channel for a single value that represents the current state of some system.

The key features of a ‘StateFlow‘ are:

- It represents a single, immutable state value that can be observed by multiple collectors

- It emits its current state to new collectors when they subscribe

- It retains its state across configuration changes

- It is backed by a ‘MutableStateFlow‘ object, which can update the state and notify all its collectors of the new value

Here’s an example of how ‘StateFlow‘ might be used to represent the state of a simple counter:

class CounterViewModel : ViewModel() {
    private val _counter = MutableStateFlow(0)
    val counter: StateFlow<Int> = _counter.asStateFlow()

    fun incrementCounter() {
        _counter.value++
    }
}

Here, we create a ‘MutableStateFlow‘ object called ‘_counter‘ that represents the current state of the system (in this case, the value of a counter). We then expose this state as a ‘StateFlow‘ object called ‘counter‘. We can update the state by simply modifying the value of ‘_counter‘. Any observers of ‘counter‘ will be notified of the new state.

**SharedFlow**

‘SharedFlow‘ is a type of ‘Flow‘ that represents a shared stream of events that can be collected by multiple collectors. Unlike ‘StateFlow‘, ‘SharedFlow‘ can emit multiple values, and does not have a concept of a "current state". Instead, it can emit any number of events to all of its collectors.

The key features of a ‘SharedFlow‘ are:

- It represents a shared stream of events that can be collected by multiple collectors

- It can emit multiple events, rather than just a single state value

- It emits new events to all collectors when they are emitted, rather than just to new collectors when they subscribe

- It may not retain its state across configuration changes, depending on how it is configured

Here’s an example of how ‘SharedFlow‘ might be used to represent a stream of messages:

val messages = MutableSharedFlow<String>()

fun sendMessage(message: String) {
    messages.emit(message)
}

Here, we create a ‘MutableSharedFlow‘ object called ‘messages‘ that represents a stream of messages. We can emit new messages to all collectors by simply calling the ‘emit‘ method. Any observers of ‘messages‘ will be notified of the new events.

**When to use each**

So, when should you use ‘StateFlow‘ and when should you use ‘SharedFlow‘? It depends on the nature of your data.

If your data is best represented as a single, immutable state value (like the value of a counter or the current state of a UI element), then ‘StateFlow‘ is probably the better choice. ‘StateFlow‘ is optimized for this use case and provides a cleaner, simpler API for managing state.

If your data is better represented as a stream of events (like a series of messages sent over a network), then ‘SharedFlow‘ is probably the better choice. It provides more flexibility in terms of emitting multiple values and broadcasting those values to all collectors.

Overall, both ‘StateFlow‘ and ‘SharedFlow‘ are powerful abstractions for representing asynchronous data in Kotlin, and choosing between them ultimately depends on the specific requirements of your use case.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics