Modify: 网络请求

This commit is contained in:
Quyunshuo
2020-08-29 11:28:13 +08:00
parent 2e4c78cdd9
commit 0d68e2a7c9
12 changed files with 211 additions and 4 deletions

View File

@@ -1,6 +1,7 @@
package com.quyunshuo.main
import com.quyunshuo.base.mvvm.m.BaseRepository
import com.quyunshuo.common.net.NetRequest
/**
* @Author: QuYunShuo
@@ -17,4 +18,35 @@ class MainRepository : BaseRepository() {
flowRequest<String> {
emit("嘿嘿")
}
/**
* 模拟使用网络请求接口
* 需要写成挂起函数
*/
suspend fun mockRequest() =
flowRequest<String> {
// 发起请求
// 并行请求可以使用 async await
// 例如
// // 创建一个新的协程进行请求
// val deferredRealtime = async {
// SendRequest.getRealtimeWeather(lng, lat)
// }
// // 创建一个新的协程进行请求
// val deferredDaily = async {
// SendRequest.getDailyWeather(lng, lat)
// }
// // 对两个请求获取结果
// val realtimeResponse = deferredRealtime.await()
// val dailyResponse = deferredDaily.await()
// 这两个协程是并行的 不是串行
val testData = NetRequest.homeService.getTestData("mock")
// 处理请求结果
// {if testData ... }
// 将请求结果或者是调用者需要的数据进行发射出去
emit(testData.msgTest)
}
}

View File

@@ -1,10 +1,14 @@
package com.quyunshuo.main
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.quyunshuo.base.mvvm.vm.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
/**
@@ -26,4 +30,26 @@ class MainViewModel : BaseViewModel<MainRepository>() {
}
}
}
fun getTestString() {
viewModelScope.launch {
mRepository.getString()
.onStart {
// 获取数据之前
// 可以做loading图之类的
}
.catch {
// 处理异常 获取数据产生的异常
}
.onCompletion {
// 获取数据完成时
}
.collectLatest {
// 拿到想要的数据
Log.d("qqq", "getTestString: $it")
}
// onStart() catch() onCompletion() 都是可选的 是flow的操作符
// 例如 mRepository.getString().collectLatest { // 拿到想要的结果 }
}
}
}