Kotlin 无法从views init从视图侦听协同路由

Kotlin 无法从views init从视图侦听协同路由,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,我正在尝试从我的flattersceneview收听我的ViewModelsMutableStateFlow。但是,在尝试从views init设置侦听器时,出现以下错误: Suspend函数“listenToBackgroundColor”只能从协同程序或另一个Suspend函数调用 class FlutterSceneView(context: Context, private val viewModel: FlutterSceneViewModelType): PlatformView {

我正在尝试从我的
flattersceneview
收听我的ViewModels
MutableStateFlow
。但是,在尝试从views init设置侦听器时,出现以下错误:

Suspend函数“listenToBackgroundColor”只能从协同程序或另一个Suspend函数调用

class FlutterSceneView(context: Context, private val viewModel: FlutterSceneViewModelType): PlatformView {
    private val context = context
    private val sceneView = SceneView(context)

    init {
        listenToBackgroundColor() // Error here
    }

    private suspend fun listenToBackgroundColor() {
        viewModel.colorFlow.collect {
            val newColor = Color.parseColor(it)
            sceneView.setBackgroundColor(newColor)
        }
    }
}
我的ViewModel:

interface FlutterSceneViewModelType {
    var colorFlow: MutableStateFlow<String>
}

class FlutterSceneViewModel(private val database: Database): FlutterSceneViewModelType, ViewModel() {
    override var colorFlow = MutableStateFlow<String>("#FFFFFF")

    init {
            listenToBackgroundColorFlow()
    }

    private fun listenToBackgroundColorFlow() {
        database.backgroundColorFlow.watch {
            colorFlow.value = it.hex
        }
    }
}
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope

我通过使用viewModel上下文解决了这个问题:

    private fun listenToBackgroundColor() {
        viewModel.colorFlow.onEach {
            val newColor = Color.parseColor(it)
            sceneView.setBackgroundColor(newColor)
        }.launchIn(viewModel.viewModelScope)
    }
我必须将以下内容导入到我的ViewModel中:

interface FlutterSceneViewModelType {
    var colorFlow: MutableStateFlow<String>
}

class FlutterSceneViewModel(private val database: Database): FlutterSceneViewModelType, ViewModel() {
    override var colorFlow = MutableStateFlow<String>("#FFFFFF")

    init {
            listenToBackgroundColorFlow()
    }

    private fun listenToBackgroundColorFlow() {
        database.backgroundColorFlow.watch {
            colorFlow.value = it.hex
        }
    }
}
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
发件人:


只能从协程调用挂起函数。我不知道还能有什么帮助,因为奇怪的是,你不知道这一点,但知道什么是流,这比协同程序的基础更高级。