Skip to Content
Kotlin 编程实践
book

Kotlin 编程实践

by Ken Kousen
July 2020
Intermediate to advanced
235 pages
3h 37m
Chinese
China Machine Press
Content preview from Kotlin 编程实践
216
13
➊ 
使用 coroutineContext 属性启动。
➋ 
为网络调用切换到 Dispatchers.IO
➌ 
切换回 Dispatchers.Main 更新 UI
一旦 activity 被销毁,任务也将被取消。
最新版本的 Android 架构组件提供了其他作用域,例如 viewModelScope,这些作用
域在清除 ViewModel 时会自动取消作业。这是 Android KTX 库的一部分,因此你需要
在构建中添加适当的依赖项:
dependencies {
// ... 与前面相同 ...
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:x.x.x"
}
这将添加 viewModelScope 属性,你可以使用该属性在任何调度器上启动协程。
13.6
协程调试
问题
如何获取运行中的协程的更多信息。
解决方案
使用 JVM 上的 -Dkotlinx.coroutines.debug 标记。
讨论
调试异步程序总是很困难的,因为可以同时运行多个任务。幸运的是,协程库包含一个
简单的调试功能。
要在调试模式下(在 JVM 上)执行协程,请使用系统属性 kotlinx.coroutines.
debug
或者,你可以通过 Java 命令行上的 -ea(启用断言)标记启用调试。
协程与结构化并发
217
调试模式为每个启动的协程都附加一个唯一的名称。为方便起见,在此处复制了示例
13-5,显示除主线程之外还启动了两个协程: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

GraphQL 学习指南

GraphQL 学习指南

Eve Porcello, Alex Banks
Java 技术手册(原书第7版)

Java 技术手册(原书第7版)

Benjamin J. Evans, David Flanagan
Python机器学习基础教程

Python机器学习基础教程

Andreas C. Müller, Sarah Guido

Publisher Resources

ISBN: 9787111659624