Flow in Android?
Flow allows us to work with a series of values that are computed or fetched asynchronously. Flow is created using a coroutine.
Entities:
1) Producer produces data that is added to the stream.
2) Intermediaries (Optional) can modify each value emitted into the stream or the stream itself without consuming the values (map, filter).
3) Consumer consumes the values from the stream.
The flow operator is used to create a producer. The collect operator is used to collect the values emitted by it. Flow can complete with exception if it is thrown inside the builder block, we can use catch intermediate operator to catch exceptions.
Types of Flow:
Cold Flow — It does not start producing values until one starts to collect them. It can have only one subscriber. e.g. flow
Hot Flow — It will produce values even if no one is collecting them. e.g. StateFlow, SharedFlow.
StateFlow vs SharedFlow:
StateFlow needs an initial value and emits it as soon as the collector starts collecting. Only emits the last known value. It has the value property, we can check the current value. It emits the value only when it is different from previous.
SharedFlow does not need an initial value so does not emit any value by default. It does not have value property. It emits all values. It can be configured to emit previous values using the replay operator.
Flow vs LiveData: