问题描述
我读过类似的主题,但找不到正确的答案:
- How to end / close a MutableSharedFlow?
- Kotlin Flow: How to unsubscribe/stop
- StateFlow and SharedFlow. Making cold flows hot using shareIn - Android 文档
- Introduce SharedFlow - 由 Roman Elizarov 发起的 GH 讨论
在我的 Repository
课上,我有一个冷的 Flow
我想分享给 2 Presenters
/ViewModels
所以我的选择是使用 shareIn
运算符.
让我们看一下 Android 文档的示例:
val latestNews: Flow<List<ArticleHeadline>> = flow {
...
}.shareIn(
externalScope,// e.g. CoroutineScope(Dispatchers.IO)?
replay = 1,started = SharingStarted.WhileSubscribed()
)
文档对 externalScope
参数的建议:
一个用于共享流的 CoroutineScope。这个范围应该比任何消费者活得更久,以在需要时保持共享流的活动。
然而,寻找关于如何停止订阅 Flow
的答案,第二个链接中投票最多的答案说:
解决方案不是取消流程,而是取消流程的范围。
对我来说,这些答案在 SharedFlow
的情况下是矛盾的。不幸的是,即使在其 Presenter
被调用后,我的 ViewModel
/onCleared
仍然收到最新数据。
如何防止?这是我如何在 Flow
/Presenter
中使用此 ViewModel
的示例:
fun doSomethingUseful(): Flow<OtherModel> {
return repository.latestNews.map(OtherModel)
如果这可能有帮助,我正在使用 MVI 架构,因此 doSomethingUseful
会对用户创建的某些意图做出反应。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)