~~~
val service = retrofit.create(RequestService::class.java)
service.getDatas().enqueue(object : Callback<DataBean> {
override fun onFailure(call: retrofit2.Call<DataBean>, t: Throwable) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onResponse(call: retrofit2.Call<DataBean>, response: Response<DataBean>) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
})
~~~
class ScrollingViewModel : ViewModel() {
private val TAG = ScrollingViewModel::class.java.simpleName
private val datas: MutableLiveData<DataBean> by lazy { MutableLiveData<DataBean>().also { loadDatas() } }
private val repository = ArticleRepository()
fun getActicle(): LiveData<DataBean> {
return datas
}
private fun loadDatas() {
GlobalScope.launch(Dispatchers.Main) {
getData()
}
// Do an asynchronous operation to fetch users.
}
private suspend fun getData() {
val result = withContext(Dispatchers.IO){
// delay(10000)
repository.getDatas()
}
datas.value = result
}
}
class ScrollingViewModel : BaseViewModel() {
private val TAG = ScrollingViewModel::class.java.simpleName
private val datas: MutableLiveData<List<Data>> by lazy { MutableLiveData<List<Data>>().also { loadDatas() } }
private val repository = ArticleRepository()
fun getActicle(): LiveData<List<Data>> {
return datas
}
private fun loadDatas() {
launchUI {
Log.i(TAG,"loadDatas1 run in ${Thread.currentThread().name}")
val result = repository.getDatas()
Log.i(TAG,"loadDatas3 run in ${Thread.currentThread().name}")
datas.value = result.data
}
// Do an asynchronous operation to fetch users.
}
}
注意看请求部分,就两句话,一句发起请求val result = repository.getDatas(),然后就是为我们的LiveData赋值了,看起有没有同步代码的感觉,这就是协程的魅力所在,为了验证我们的请求没有阻塞主线程,我打印了日志
06-19 12:26:35.736 13648-13648/huaan.com.mvvmdemo I/ScrollingViewModel: loadDatas start run in main
06-19 12:26:45.743 13648-13684/huaan.com.mvvmdemo I/ScrollingViewModel: request run in DefaultDispatcher-worker-1
06-19 12:26:46.227 13648-13648/huaan.com.mvvmdemo I/ScrollingViewModel: loadDatas end run in main
请发表评论