Open geziin opened 2 years ago
也可以自定义协程的扩展 在Dialog使用MainScope()
fun <T> CoroutineScope.http(
request: suspend () -> BaseResponse<T>,
response: (T) -> Unit,
error: (Throwable) -> Unit = {}
): Job {
return launch {
kotlin.runCatching {
request()
}.onSuccess {
response(it.getResponseData())
}.onFailure {
error(it)
}
}
}
class MyDialog(context: Context) : Dialog(context) {
........
var exampleJob: Job? = null
fun httpExample() {
exampleJob?.cancel()
exampleJob = MainScope()?.http(
request = { apiService.getUserInfo() },
response = { }
)
}
override fun cancel() {
super.cancel()
exampleJob?.cancel()
}
}
扩展一点来讲,api接口是suspend关键字修饰的,只要可以开启协程都可以进行网络请求 如在自定义线程中,执行网络任务
class TaskTask1() : Runnable {
override fun run() {
val data = runBlocking { //阻塞当前线程
try {
ApiClient.appApi.getBanner()
} catch (e: Exception) {
null
}
}
//线程继续执行
if (data?.isSucces()==true) {
}
}
}
建议试试协程网络请求同步写法例如Net, 没有回调