导入

  1. ...
  2. dependencies {
  3. ...
  4. implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.1"
  5. }

使用

非 ViewModel

  1. // 非 ViewModel
  2. CoroutineScope(Dispatchers.Main).launch {
  3. val user = api.getUser() // 👈 网络请求(IO 线程)
  4. nameTv.text = user.name // 👈 更新 UI(主线程)
  5. }

ViewModel

  1. // ViewModel
  2. // implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0"
  3. viewModelScope.launch {
  4. val user = api.getUser() // 👈 网络请求(IO 线程)
  5. nameTv.text = user.name // 👈 更新 UI(主线程)
  6. }

替换 Rx

Rx

  1. // Api 接口
  2. interface ApiService {
  3. @GET("hello")
  4. fun hello(@QueryMap map: HashMap<String, String>): Observable<Result>
  5. }
  6. fun fetchHello() {
  7. apiService.hello(map)
  8. .subscribeOn(Schedulers.io())
  9. .observeOn(AndroidSchedulers.mainThread())
  10. .subscribe({
  11. // result
  12. }, {
  13. // throwable
  14. }, {
  15. // complete
  16. })
  17. }

协程

  1. // Api 接口
  2. interface ApiService {
  3. @GET("hello")
  4. suspend fun hello(@QueryMap map: HashMap<String, String>): Result
  5. }
  6. fun fetchHello() {
  7. CoroutineScope(Dispatchers.Main).launch {
  8. try {
  9. // 请求网络
  10. val result = withContext(Dispatchers.IO) { // 👈 切换到 IO 线程,并在执行完成后切回 UI 线程
  11. apiService.hello(map) // 👈 将会运行在 IO 线程
  12. }
  13. // 请求成功
  14. nameTv.text = result // 👈 回到 UI 线程更新 UI
  15. } catch (e: Exception) {
  16. // 请求异常
  17. }
  18. }
  19. }