外观
什么是 CoroutineScope?为什么推荐在 ViewModel 中使用 viewModelScope?
标准回答
CoroutineScope 定义协程使用的上下文和取消范围。viewModelScope 与 ViewModel 绑定,ViewModel 被清除时会取消其中的协程;配置变更时 ViewModel 通常保留,因此适合延续相关业务任务。它不保证进程死亡后任务继续。
通俗例子
页面业务由 ViewModel 持有,viewModelScope 中的任务通常在 ViewModel 清理时取消。它不是“自动切到后台”的同义词。
深入解释
**Scope 和线程不是一回事:**Scope 管一组任务的父子关系和取消;Dispatcher 决定执行位置。即使任务放进协程,若仍在 Main 上做阻塞计算,主线程照样会卡。
**取消发生在什么边界:**viewModelScope 跟随 ViewModel,配置变化时 ViewModel 可能继续存在;真正清理 ViewModel 时任务才取消。阻塞调用是否及时停止还取决于它是否支持取消。
内容来源
- Android · AI Agent 知识手册 · 原条目
4.2.1