SharingStarted.WhileSubscribed vs Lazily

There is SharingStarted.WhileSubscribed and SharingStarted.Lazily both are used Flow.stateIn() of Android Platform.
I read the explanation in the official documentation, asked chatgpt, and googled it.
But I’m not sure what the difference between the two is.
Does anyone know the details of the difference?

I would appreciate it if you could let me know.

>Solution :

The main difference between SharingStarted.WhileSubscribed and SharingStarted.Lazily is the lifecycle of a producer.

  1. SharingStarted.Lazily starts sharing data when the first subscriber appears and after that the flow will be kept active forever. So after sharing was started it will never stop.
  2. SharingStarted.WhileSubscribed starts sharing data only if there are active subscribers. So it stops immediately when the last subscriber disappears.

Note: that in case of SharingStarted.WhileSubscribed you can provide stopTimeoutMillis to set some timeout, which configures a delay between the disappearance of the last subscriber and the stopping of the sharing coroutine. By default, it is zero, that’s why it stops immediately.

Leave a Reply