Kotlin Flows: The Graduated Coroutine  -  I I

The Types

Well, this is part II of this series of articles. If you have a basic idea regarding Kotlin Flow, you are good to start here. Otherwise, have look at part I of this series.

Cold Flow vs Hot Flow

In the previous article, we just discussed what actually a flow is, along with a very basic example of it.

Let’s move to the types of Kotlin Flow. Well, it can basically be divided into 2 broad categories Cold Flow and Hot Flow.

Flow in Kotlin is something that helps us handle a stream of data asynchronously, that executes sequentially. Generally, it emits data over a period of time and updates the collectors of the flow. But the point here is what happens when we do not have any collector for the flow? Does that still emit all the changes or does that wait for the collectors to register for collection?

Hmm!

The question asked above is the answer to two broad categories of Kotlin Flow. Well, if the flow emits irrespective of the collector being registered or not, then it comes under the category of Hot Flow. Whereas, if the flow does not emit until a collector is there to collect the emitted data, then it is a Cold Flow.

StateFlow and SharedFlow are considered to be Hot Flow. We will discuss StateFlow and SharedFlow in detail, very soon. soon-cat.gif

StateFlow

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.

From the docs, the StateFlow are stated as three things - observable, flow and a state-holder.

You must be thinking about, isn’t that similar to LiveData?

Well, if you have that question, then you’re heading in the right direction. StateFlow provides LiveData like services (minus LifeCycle awareness) along with all the capabilities of a flow. It is also seen as a replacement for LiveData in the Android community. Well, that will be an interesting point to discuss, but that is out of the scope of this article. Maybe later.

Okay, so we just discussed what is a StateFlow. Let’s jump into the code super fast.

For declaring StateFlow, we can use the following set up, in our ViewModel:

private val _stateFlow = MutableStateFlow("Click Random News, to get one.")
var stateFlow = _stateFlow.asStateFlow()

If you notice, we have a Mutable State Flow (_stateFlow), which isn’t allowed to be accessed from outside of ViewModel. And then we have an immutable version of it, to which other components can subscribe to / collect with.

For updating the value for StateFlow, it is quite similar to how we do it for LiveData:

fun randomNews() {
    _stateFlow.value = newsList[Random.nextInt(0, 4)]
}

Nothing fancy with the collection of the StateFlow, as well:

val newsViewModel = viewModel<LatestNewsViewModel>()
val news = newsViewModel.stateFlow.collectAsState("")
                Surface(color = MaterialTheme.colors.surface) {
    Column(modifier = Modifier.fillMaxWidth()) {
        Box(modifier = Modifier.size(20.dp))
        Button(
            onClick = { newsViewModel.randomNews() },
            modifier = Modifier
                .size(200.dp, 50.dp)
                .align(CenterHorizontally),
        ) {
            Text(text = "Random News")
        }
        FlashNews(news)
    }
}

StateFlowDemo.gif

SharedFlow

A hot Flow that shares emitted values among all its collectors in a broadcast fashion, so that all collectors get all emitted values. A shared flow is called hot because its active instance exists independently of the presence of collectors.

In simple words, the SharedFlow is a flow specifically meant to be shared among multiple collectors, such that all the emitted values are observed by them.

Enough said, let’s jump to the part that tells how to use it.

Basically, we can use shareIn function of flow, which returns a SharedFlow, or we can also use MutableSharedFlow to initialize a SharedFlow instance.

The SharedFlow behaviour can be altered using the following properties:

  • replay lets you decide the number of previously emitted values to be sent back to the observing collectors.
  • onBufferOverflow lets you decide the strategy for shedding off values in case of buffer overflow. It can be
    • SUSPEND (Default) - the caller is suspended
    • DROP_LATEST - the latest value is dropped
    • DROP_OLDEST - the oldest value is dropped
  • subscriptionCount lets you restrict the number of allowed subscribers.

Well, that’s it, for now. that's a wrap.gif Thanks for reading this article! Leave a comment below if you have any questions. I will be back with a step further into Flow. Till then, take care.

The code can also be found on Github: [github.com/AbhasVohra/Flow_FlashNews](https..