Kotlin协程入门到实战全部三篇文章:
- Kotlin协程Coroutines入门到实战:(一)理解异步回调的本质
- Kotlin协程Coroutines入门到实战:(二)Coroutines初体验
- Kotlin协程Coroutines入门到实战:(三)Coroutines+Retrofit+ViewModel+LiveData实现MVVM客户端架构
我们在前两篇文章中讲解了Kotlin协程的基本用法和所解决的关键性问题,接下来让我们来看看在实际项目中该怎么使用Kotlin协程这一利器呢。接下来一起来将Kotlin协程与Jetpack中的架构组件结合起来搭建个简单的项目吧。以下是此Demo的效果:
可以看到功能其实很简单,界面由一个按钮和三个图片组成。每次按下刷新按钮,就都会从网络上获取三张图片显示到界面上。从网络上获取图片的时候刷新按钮变为不可用状态,刷新完成后按钮恢复可用状态。
1.添加依赖
//添加Retrofit网络库和gsonConverter的依赖,注意一定要2.6.0版本以上
implementation 'com.squareup.retrofit2:retrofit:2.7.0'
implementation 'com.squareup.retrofit2:converter-gson:2.7.0'
//添加Jetpack中架构组件的依赖,注意viewmodel要添加viewmodel-ktx的依赖
implementation "androidx.lifecycle:lifecycle-livedata:2.1.0"
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0'
implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"
//添加Glide的依赖用于图片加载
implementation 'com.github.bumptech.glide:glide:4.10.0'
这里需要注意的是retrofit
版本要求2.6.0以上,因为2.6.0以上的retrofit
对于Kotlin协程提供了不错的支持,用起来也更方便。另外添加ViewModel
的依赖一定要添加Kotlin版本的,因为这个版本为我们提供了viewModelScope
这个协程范围的支持,这让我们可以方便地将生命周期管理和网络请求自动取消的任务交给它。
2.编写UI界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="10dp"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:text="refresh"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scaleType="centerCrop"
android:layout_marginTop="10dp"/>
<ImageView
android:id="@+id/imageView2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scaleType="centerCrop"
android:layout_marginTop="10dp"/>
<ImageView
android:id="@+id/imageView3"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scaleType="centerCrop"