导入
...dependencies { ... implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.1"}
使用
非 ViewModel
// 非 ViewModelCoroutineScope(Dispatchers.Main).launch { val user = api.getUser() // 👈 网络请求(IO 线程) nameTv.text = user.name // 👈 更新 UI(主线程)}
ViewModel
// ViewModel// implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0"viewModelScope.launch { val user = api.getUser() // 👈 网络请求(IO 线程) nameTv.text = user.name // 👈 更新 UI(主线程)}
替换 Rx
Rx
// Api 接口interface ApiService { @GET("hello") fun hello(@QueryMap map: HashMap<String, String>): Observable<Result>}fun fetchHello() { apiService.hello(map) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ // result }, { // throwable }, { // complete })}
协程
// Api 接口interface ApiService { @GET("hello") suspend fun hello(@QueryMap map: HashMap<String, String>): Result}fun fetchHello() { CoroutineScope(Dispatchers.Main).launch { try { // 请求网络 val result = withContext(Dispatchers.IO) { // 👈 切换到 IO 线程,并在执行完成后切回 UI 线程 apiService.hello(map) // 👈 将会运行在 IO 线程 } // 请求成功 nameTv.text = result // 👈 回到 UI 线程更新 UI } catch (e: Exception) { // 请求异常 } }}