I've read similar topics but couldn't find a proper answer:
- How to end / close a MutableSharedFlow?
- Kotlin Flow: How to unsubscribe/stop
- StateFlow and SharedFlow. Making cold flows hot using shareIn - Android docs
- Introduce SharedFlow - GH discussion started by Roman Elizarov
In my Repository
class I have a cold Flow
that I want to share to 2 Presenters
/ViewModels
so my choice is to use shareIn
operator.
Let's take a look on Android docs' example:
val latestNews: Flow<List<ArticleHeadline>> = flow {
...
}.shareIn(
externalScope, // e.g. CoroutineScope(Dispatchers.IO)?
replay = 1,
started = SharingStarted.WhileSubscribed()
)
What docs suggests for externalScope
parameter:
A CoroutineScope that is used to share the flow. This scope should live longer than any consumer to keep the shared flow alive as long as needed.
However, looking for answer on how to stop subscribing a Flow
, the most voted answer in 2nd link says:
A solution is not to cancel the flow, but the scope it's launched in.
For me, these answers are contradictory in SharedFlow
's case. And unfortunately my Presenter
/ViewModel
still receives newest data even after its onCleared
was called.
How to prevent that? This is an example how I consume this Flow
in my Presenter
/ViewModel
:
fun doSomethingUseful(): Flow<OtherModel> {
return repository.latestNews.map(OtherModel)
If this might help, I'm using MVI architecture so doSomethingUseful
reacts to some intents created by the user.
doSomethingUseful
flow doesn't explicitly have a scope. The only scope I see is located in myBasePresenter
/BaseViewModel
class that subscribes to all intents (MVI-specific behaviour). Should I cancel it then? – adek111