Android state flow and shared flow

Android state flow and shared flow

If you are getting tired by reading all the stuff on the internet related state flow and shared flow and want to know what they actually are then in this blog I have shared some easy understanding of it and check out all the code snippets for better understanding.

State Flow:

It's a flow api which stores the current and updated state of value. And notify the consumer if any change in state occurs.

Implementation:

Following is a code of view Model and an activity. Where ViewModel behaves as Producer and Activity behave as a consumer. For State flow we will make two instances mutable and immutable as you can see in the view model class. _stateFlow is mutable and stateFlow is an immutable instance. All operations of altering the state of value are applied on _stateFlow in the view model and the stateFlow instance is used by consumers so they can collect the data and its changes.

Producer:

Consumer:

Shared Flow:

SharedFlow is a Flow that allows for sharing itself between multiple collectors or consumers, so that only one flow is effectively run for all of the simultaneous collectors.

Implementation:

As I have made two instances of shared flow one is mutable and other immutable. immutable instance will be used for collecting the data, and we will emit the data using mutable instance. By calling squareNumber() function we will emit the data in flow and collect it from two collectors or consumers.

Code: state flow and share flow