gpt4 book ai didi

android - SharedFlow 不从发射中收集

转载 作者:行者123 更新时间:2023-12-05 01:52:07 26 4
gpt4 key购买 nike

在我的 ViewModel 中,我发出 API 请求并使用 StateFlowSharedFlow 与 fragment 通信。在发出 API 请求时,我可以轻松地更新状态流的值并成功收集到 fragment 中。

但在发出请求之前,我使用 SharedFlow 发出了一些 bool 值,并且它没有被收集到 Fragment 中。谁能帮我看看为什么会这样?

class MainViewModel: ViewModel() {
private val _stateFlow = MutableStateFlow(emptyList<Model>())
val stateFlow = _stateFlow.asStateFlow()

private val _loading = MutableSharedFlow<Boolean>()
val loading = _loading.asSharedFlow()

suspend fun request() {
_loading.emit(true)
withContext(Dispatchers.IO) {
/* makes API request */
/* updates _stateFlow.value */
/* stateFlow value is successfully collected */
}
_loading.emit(false) // emitting boolean value
}
}
class MyFragment : Fragment(R.layout.fragment_my) {
// ...

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
lifecycleScope.launchWhenStarted {
viewModel.request()
/* stateFlow is collected and triggered - working properly */

viewModel.loading.collectLatest { // <- NOT COLLECTING - WHY?
Log.d(this::class.simpleName, "onViewCreated: $it") // <- NOT LOGGING
}
}
}
}

最佳答案

SharedFlow 是一个热门流。也许你应该创建它

MutableSharedFlow(
replay = 0,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
extraBufferCapacity = 1
)

MutableSharedFlow(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)

关于android - SharedFlow 不从发射中收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71734781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com