0

我正在尝试从flow.

视图模型

val events = MutableStateFlow<HomeEvent>(HomeEvent.Empty)
val uiEvents: StateFlow<HomeEvent> = events

private suspend fun emitEvent(homeEvent: HomeEvent) {
    events.emit(homeEvent)
}

private fun downloadHomeData() {
    viewModelScope.launch(dispatchers.io + exceptionHandler) {
      longRunningTaskSync()
      emitEvent(HomeEvent.DisplayHomeAnimation())

      longRunningTaskSync2()
      emitEvent(HomeEvent.DisplayProgressiveLoadingImages())

      longRunningTaskSync3()
      emitEvent(HomeEvent.DisplayTitles())

      emitEvent(HomeEvent.DisplayProgressiveLoadingPosts())
      emitEvent(HomeEvent.DisplayProgressiveLoadingComments())
      emitEvent(HomeEvent.DisplayKpi())
    }
  }

首页片段

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    lifecycleScope.launch {
      repeatOnLifecycle(Lifecycle.State.STARTED) {
        try {
          viewModel.uiEvents.collect { event ->
            when (event) {
              is HomeEvent.DisplayHomeAnimation -> { }
              is HomeEvent.DisplayProgressiveLoadingImages -> { }
              is HomeEvent.DisplayKpi -> { }
              is HomeEvent.DisplayTitles -> { }
              is HomeEvent.DisplayProgressiveLoadingPosts -> { }
              is HomeEvent.DisplayProgressiveLoadingComments -> { }
              is HomeEvent.Empty -> { }
            }
          }
        } catch (t: Throwable) {
        }
      }
    }
} 

在上面的示例中,MutableStateFlow未能发出某些事件。但是每次我delay(200)在连续发射之间放置一个,一切都会正常工作。

除非我错了,否则它应该按发射顺序发射所有事件。这是预期的行为吗?我错过了文档中的某些内容吗?还是我做错了什么?

4

0 回答 0