从视图中侦听协同程序不能从视图init中完成



我正在尝试从FlutterSceneView收听ViewModelsMutableStateFlow。但是,当我试图从视图init设置侦听器时,我得到了以下错误:

Suspend function 'listenToBackgroundColor' should be called only from a coroutine or another suspend function

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)
}
}
}

我的视图模型:

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
}
}
}

.watch调用是我添加的一个助手,这样就可以使用Kotlin多平台向iOS公开它,看起来如下,但如果需要,我可以使用collect

fun <T> Flow<T>.asCommonFlow(): CommonFlow<T> = CommonFlow(this)
class CommonFlow<T>(private val origin: Flow<T>) : Flow<T> by origin {
fun watch(block: (T) -> Unit): Closeable {
val job = Job()
onEach {
block(it)
}.launchIn(CoroutineScope(Dispatchers.Main + job))
return object : Closeable {
override fun close() {
job.cancel()
}
}
}
}

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

private fun listenToBackgroundColor() {
viewModel.colorFlow.onEach {
val newColor = Color.parseColor(it)
sceneView.setBackgroundColor(newColor)
}.launchIn(viewModel.viewModelScope)
}

我不得不将以下内容导入我的ViewModel:

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope

来自:

implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0")

最新更新