首页 > 解决方案 > 从 Java 收集的 SharedFlow 不起作用

问题描述

我有一小部分活动需要在后台生成的某些事件上重新启动。由于这将是一个短期的解决方法,我认为侵入性最小的方法是在存储库中拥有一个共享流,从 UI 一路观察,但由于某种原因它不起作用:我可以看到价值发出,但 UI 不对其作出反应。

我当前的代码:

// Repository
val myEventFlow = MutableSharedFlow<Unit>(replay = 0)
 
// Use Case to emit the event (dummy impl, just to test the mechanism is working)
operator fun invoke() = runBlocking {
    myExistingRepository.myEventFlow.emit(Unit)
}
 
// Use Case class to fetch the flow
operator fun invoke() = myExistingRepository.myEventFlow.asSharedFlow()
 
// View Model (in Java, can't convert it)
public LiveData<Unit> myEvent() {
  return FlowLiveDataConversions.asLiveData(getMyEventUseCase.invoke());
}
 
// Activity (also in Java)
viewModel.myEvent().observe(this, event -> activityHelper.startWithClearStack(getClass()));
 
// Activity Helper (dummy impl just to see the event being reacted to)
fun startWithClearStack(activity: Class<out Activity>) {
    Timber.d("DEBUG: restarting class $activity")
}

我可以确认事件已发出(在调试中,包含的行emit()已被执行)但是 Activity 中的观察者永远不会被激活。知道为什么吗?

提前致谢

标签: javaandroidkotlinkotlin-coroutineskotlin-sharedflow

解决方案


推荐阅读