How to use Flow in Android Programming

Flow is a stream processing API in Kotlin developed by JetBrains1It’s an implementation of the Reactive Stream specification, an initiative whose goal is to provide a standard for asynchronous stream processing1Jetbrains built Kotlin Flow on top of Kotlin Coroutines, which means that you can use suspend functions to produce and consume values asynchronously2.

In this blog post, I will show you how to use Flow in your Android project to handle live data updates and endless streams of data. You will learn how to create flows, modify them, collect them, and use StateFlow and SharedFlow to share state and events across your app.

Creating a flow

To create flows, use the flow builder APIs. The flow builder function creates a new flow where you can manually emit new values into the stream of data using the emit function2. For example, you can use a flow to receive live updates from a network API:

class NewsRemoteDataSource( private val newsApi: NewsApi, private val refreshIntervalMs: Long = 5000 ) { val latestNews: Flow<List<ArticleHeadline>> = flow { while(true) { val latestNews = newsApi.fetchLatestNews() emit(latestNews) // Emits the result of the request to the flow delay(refreshIntervalMs) // Suspends the coroutine for some time } } } // Interface that provides a way to make network requests with suspend functions interface NewsApi { suspend fun fetchLatestNews(): List<ArticleHeadline> }

The flow builder is executed within a coroutine. Thus, it benefits from the same asynchronous APIs, but some restrictions apply:

Modifying the stream

You can use various operators to transform or filter the values emitted by a flow. For example, you can use map to apply a function to each value, filter to remove unwanted values, or combine to merge two flows into one2. For example, you can use map to convert the list of article headlines into a list of article titles:

val latestNewsTitles: Flow<List<String>> = latestNews.map { headlines -> headlines.map { headline -> headline.title } }

You can also use operators that are specific to flows, such as debounce or distinctUntilChanged. These operators help you deal with flows that emit values too frequently or unnecessarily2. For example, you can use debounce to ignore values that are emitted in quick succession:

val debouncedNewsTitles: Flow<List<String>> = latestNewsTitles.debounce(1000) // Ignores values that are emitted less than 1000 ms apart

Collecting from a flow

To start receiving values from a flow, you need to collect it. Collecting is a terminal operation that triggers the execution of the flow and invokes a given action for every value emitted by the flow2. You need to collect flows from a coroutine or a suspend function. For example, you can collect the debounced news titles from an activity:

class LatestNewsActivity : AppCompatActivity() { private val newsRemoteDataSource = // getDataSource() override fun onCreate(savedInstanceState: Bundle?) { ... // Start a coroutine in the lifecycle scope lifecycleScope.launch { // repeatOnLifecycle launches the block in a new coroutine every time the // lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED. repeatOnLifecycle(Lifecycle.State.STARTED) { // Trigger the flow and start listening for values. newsRemoteDataSource.debouncedNewsTitles.collect { titles -> // Update UI with new titles } } } } }

Note that collecting from a flow can be a suspending operation if the flow is infinite or slow. This means that you should not collect from multiple flows sequentially in the same coroutine, as this will block the execution of the next collect until the previous one finishes. Instead, you should launch multiple coroutines or use other operators like zip or flatMapMerge to collect from multiple flows concurrently2.

StateFlow and SharedFlow

StateFlow and SharedFlow are Flow APIs that enable flows to optimally emit state updates and emit values to multiple consumers3.

StateFlow is a state-holder observable flow that emits the current and new state updates to its collectors. The current state value can also be read through its value property. To update state and send it to the flow, assign a new value to the value property of the MutableStateFlow class3.

In Android, StateFlow is a great fit for classes that need to maintain an observable mutable state. For example, you can use StateFlow to expose UI state from a ViewModel:

class LatestNewsViewModel( private val newsRepository: NewsRepository ) : ViewModel() { // Backing property to avoid state updates from other classes private val _uiState = MutableStateFlow(LatestNewsUiState.Success(emptyList())) // The UI collects from this StateFlow to get its state updates val uiState: StateFlow<LatestNewsUiState> = _uiState init { viewModelScope.launch { newsRepository.favoriteLatestNews // Update View with the latest favorite news // Writes to the value property of MutableStateFlow, // adding a new element to the flow and updating all // of its collectors .collect { favoriteNews -> _uiState.value = LatestNewsUiState.Success(favoriteNews) } } } } // Represents different states for the LatestNews screen sealed class LatestNewsUiState { data class Success(val news: List<ArticleHeadline>): LatestNewsUiState() data class Error(val exception: Throwable): LatestNewsUiState() }

Unlike a cold flow built using the flow builder, a StateFlow is hot: collecting from the flow doesn’t trigger any producer code. A StateFlow is always active and in memory, and it becomes eligible for garbage collection only when there are no other references to it from a garbage collection root. When a new consumer starts collecting from the flow, it receives the last state in the stream and any subsequent states. You can find this behavior in other observable classes like LiveData3.

SharedFlow is an observable hot flow that emits values only when active collectors are present. Unlike StateFlow, SharedFlow does not have any initial value nor does it store any value at all. To emit values into SharedFlow use its emit function3.

In Android, SharedFlow is useful for sharing events among multiple consumers without having any initial value or state associated with them. For example, you can use SharedFlow to broadcast user input events across your app:

class UserInputManager { // Creates an instance of MutableSharedFlow with zero replay buffer size, // meaning that only new events will be emitted by this SharedFlow. private val _userInputEvents = MutableSharedFlow<UserInputEvent>() // Exposes only SharedFlow interface so other classes cannot modify it. val userInputEvents: SharedFlow<UserInputEvent> = _userInputEvents fun onUserInput(event: UserInputEvent) { viewModelScope.launch { _userInputEvents.emit(event) // Emits event into SharedFlow } } } // Represents different types of user input events sealed class UserInputEvent { data class Tap(val x: Float, val y: Float): UserInputEvent() data class Swipe(val direction: Direction): UserInputEvent() }

To collect from StateFlow or SharedFlow, you can use any terminal operator like collect or first as with any other flow.

Conclusion

In this blog post, you learned how to use Flow in your Android project to handle live data updates and endless streams of data. You learned how to create flows, modify them, collect them, and use StateFlow and SharedFlow to share state and events across your app.

If you want to learn more about Flow and other Kotlin features for Android development, check out these resources:

I hope you enjoyed this blog post and found it useful. Happy coding! 😊

Author: John Rowan

I am a Senior Android Engineer and I love everything to do with computers. My specialty is Android programming but I actually love to code in any language specifically learning new things.

Author: John Rowan

I am a Senior Android Engineer and I love everything to do with computers. My specialty is Android programming but I actually love to code in any language specifically learning new things.

%d bloggers like this: