Flow in Android?
Flow vs LiveData.

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:

  • LiveData operates on the main thread, while Flow operates on coroutines without blocking the main thread.
  • Transformation operators are executed on the main thread in Live data. Operators in Flow are suspend functions.
  • LiveData is lifecycle aware, flow is not.
  • Flow needs coroutine environment to execute.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了