我只是在学习 StateFlow。我有一个简单的 StateFlow 来观察:
private val _userClickedAction = MutableStateFlow( Event(false))
val userClickedAction: StateFlow<Event<Boolean>> = _userClickedAction.stateIn(
scope = viewModelScope,
started = WhileSubscribed(5000),
initialValue = Event(false)
)
我试图在这样的活动中观察它:
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
valuePropViewModel.userClickedAction.collect {
valuePropViewModel.actionContext.runActionNamed(SECOND_OPTION_SELECTED)
}
}
}
它不会编译,我收到编译错误:
Type mismatch. Required: FlowCollector<Event<Boolean>> Found: () → Unit
我在用着:
// 生命周期组件
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
其中 $lifecycle_version = 2.4.0