The main difference between SharingStarted.WhileSubscribed
and SharingStarted.Lazily
is the lifecycle of a producer.
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.
SharingStarted.WhileSubscribed
starts sharing data only if there are active subscribers. So it stops immediately when the last subscriber disappears.
- Also there is
SharingStarted.Eagerly
strategy. It just stars immediately and never stops.
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.