Exploring StateFlow and SharedFlow
In this section, we will dive into StateFlow
and SharedFlow
. SharedFlow
and StateFlow
are Flows that are hot streams, unlike a normal Kotlin Flow, which are cold streams by default.
A Flow is a cold stream of data. Flows only emit values when the values are collected. With SharedFlow
and StateFlow
hot streams, you can run and emit values the moment they are called and even when they have no listeners. SharedFlow
and StateFlow
are Flows, so you can also use operators on them.
A SharedFlow
allows you to emit values to multiple listeners. SharedFlow
can be used for one-time events. The tasks that will be done by the SharedFlow
will only be run once and will be shared by the listeners.
You can use MutableSharedFlow
and then use the emit
function to send values to all the collectors.
In the following example, SharedFlow
is used in MovieViewModel
for the list of movies fetched:
class MovieViewModel : ViewModel() {
...