Jetpack Compose使用lifecycleScope遇接收者类型不匹配问题
问题:ViewModel中使用lifecycleScope报错“Unresolved reference”
更新:正如ianhanniballake在评论中指出,使用
viewModelScope替代lifecycleScope即可解决该问题。
我在Android原生Jetpack Compose应用中尝试使用androidx.lifecycle.lifecycleScope,已在build.gradle中添加以下依赖:
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1' implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.5.1' implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1'
已在MainViewModel中导入:
import androidx.lifecycle.lifecycleScope
导入无错误,悬浮查看可显示正确的来源信息,但在代码中引用lifecycleScope时:
fun isSplashScreenOptChecked() { lifecycleScope.launch() { userPrefRepo.shouldDisplaySplashScreen().collect { withContext(Dispatchers.Main) { showSplashScreen.value = it } } } }
出现错误:
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public val LifecycleOwner.lifecycleScope: LifecycleCoroutineScope defined in androidx.lifecycle
原因分析
lifecycleScope是LifecycleOwner接口的扩展属性,只有Activity、Fragment这类实现了LifecycleOwner的组件才能直接调用。而ViewModel本身并不实现LifecycleOwner接口,所以直接在ViewModel里用lifecycleScope会触发接收者类型不匹配的错误。
解决方法
ViewModel有专门配套的协程作用域viewModelScope,用法如下:
- 替换导入语句:
import androidx.lifecycle.viewModelScope
- 修改代码中的协程作用域:
fun isSplashScreenOptChecked() { viewModelScope.launch { userPrefRepo.shouldDisplaySplashScreen().collect { showSplashScreen.value = it } } }
额外说明:viewModelScope会在ViewModel销毁时自动取消所有关联的协程,无需手动管理;而且它默认使用Dispatchers.Main.immediate调度器,所以原来的withContext(Dispatchers.Main)可以直接去掉,简化代码。
内容的提问来源于stack exchange,提问作者Dave Westerman
相关产品推荐
相关产品推荐

