1

我只是在学习 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

4

1 回答 1

1

显然,我使用了错误版本的收集。

implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.4.0-beta01")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")

import kotlinx.coroutines.flow.collect 

类型不匹配推断类型为 () -> Unit 但应为 FlowCollector<Int>

于 2021-11-09T14:39:16.937 回答