KMP桌面平台Coroutine Dispacher缺失问题求助
KMP桌面平台协程调度器缺失问题解决
正在学习KMP与Compose Multiplatform,使用Voyager作为导航及ViewModel替代方案。负责数据获取的Screen Model单独测试无问题,但桌面平台运行时出现协程取消错误,具体信息如下:
错误日志
[CoroutineName(ui.MainScreen:ui.MainScreenModel:default:ScreenModelCoroutineScope), StandaloneCoroutine{Cancelled}@66207bc1, Dispatchers.Main[missing]]
相关代码
MainScreenModel.kt
class MainScreenModel : ScreenModel { private val _manga: MutableStateFlow<List<MangaDto>> = MutableStateFlow(emptyList()) val manga = _manga.asStateFlow() init { screenModelScope.launch { _manga.update { Greeting().getPopularManga() } } } }
MainScreen.kt
internal class MainScreen : Screen { @Composable override fun Content() { val screenModel = rememberScreenModel { MainScreenModel() } val searchQuery by screenModel.searchQuery.collectAsState() val manga by screenModel.manga.collectAsState() Column( verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxSize() .padding(8.dp) ) { TextField( value = searchQuery, onValueChange = { _newSearchQuery: String -> screenModel.onEvent( MainScreenModel.MainScreenEvent.OnSearchQueryChanged( _newSearchQuery ) ) }, shape = RoundedCornerShape(8.dp), leadingIcon = { Icon( imageVector = Icons.Default.Search, contentDescription = null ) }, colors = TextFieldDefaults.textFieldColors( focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, ), placeholder = { Text( text = "Search", fontWeight = FontWeight.Bold, ) }, modifier = Modifier.width(700.dp) ) LazyVerticalGrid( columns = GridCells.FixedSize(150.dp), contentPadding = PaddingValues(4.dp), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp) ) { items(manga) { manga_ -> MangaCard( id = manga_.id, title = manga_.attributes.title.en ?: manga_.attributes.title.romanized.orEmpty(), imageUrl = "https://uploads.mangadex.org/covers/${manga_.id}/${manga_.relationships.find { it.type == "cover_art" }?.attributes?.fileName.orEmpty()}", onClicked = { } ) } } } } }
问题原因
桌面平台(基于Swing)的Dispatchers.Main调度器并未包含在commonMain的协程核心依赖中,需要单独添加桌面端的协程调度器实现。Android端默认内置了Main调度器,所以不会出现此问题,但桌面端缺失导致协程无法找到正确的调度器,最终被取消。
解决步骤
- 在项目的
desktopMain依赖配置中添加Swing协程调度器依赖,版本需与commonMain中的协程核心版本保持一致:
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-swing:1.7.3")
(请替换为你使用的协程版本号)
- 重新同步项目并运行桌面端,此时
Dispatchers.Main会正确指向Swing的事件调度线程,协程可正常执行。
内容的提问来源于stack exchange,提问作者lelestacia
相关产品推荐
相关产品推荐

