美文网首页
协程的简单使用

协程的简单使用

作者: Grayson丶Wu | 来源:发表于2020-06-23 11:11 被阅读0次

1、协程作用范围。

  • 全局有效。
// 开启协程
GlobalScope.launch(Dispatchers.Main) {
    // TODO
}
  • 生命周期内有效。
// 定义一个管理协程工作的工具,例如网络请求时,中断操作。
private val viewModelJob = SupervisorJob()
// 定义一个有作用在主线程且可管理的作用域。
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
// 开启协程
uiScope.launch() {
    // TODO
}

override fun onCleared() {
    super.onCleared()
    //生命周期结束时回收,类似Rxjava的Dispose。
    viewModelJob.cancel()
}

1、基本使用。

  • 开启同步协程。
GlobalScope.launch(Dispatchers.Main) {
    L.d("1")
    // 同步协程会在遇到协程时挂起,和阻塞线程不是一个概念。
    GlobalScope.launch(Dispatchers.IO) {
        Thread.sleep(2000)
        L.d("2")
    }
    L.d("3")
}

输出:

123

  • 开启异步协程。
GlobalScope.launch(Dispatchers.Main) {
    L.d("1")
    var deferred1 = async { 
        GlobalScope.launch(Dispatchers.IO) {
            Thread.sleep(1000)
            L.d("2")
        }
    }
    var deferred2 = async { 
        GlobalScope.launch(Dispatchers.IO) {
            Thread.sleep(2000)
            L.d("3")
        }
    }
    deferred1.await()
    deferred2.await()
    L.d("4")
}

输出:

1234

2、协程的缩写。

fun coroutine() {
    GlobalScope.launch(Dispatchers.Main) {
        // TODO
    }
}

可以写成:

// suspend 是协程标签,用于编译器检查协程方法,本身没有意义。
suspend fun coroutine() = withContext(Dispatchers.Main) {
    // TODO
}

3、协程的挂起回调。

suspend inline fun <reified T : Any> getHttpModel(
    url: String,
    header: HttpHeaders?,
    params: HttpParams?,
    isUseCache: Boolean
) = suspendCoroutine<T> {
    val type = object : TypeToken<T>() {}.type
    val get = MMCHttp.get<T>(url)
    if (params != null) {
        get.params(params)
    }
    if (header != null) {
        get.headers(header)
    }
    if (isUseCache) {
        get.cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
        get.cacheKey(url)
        get.cacheTime(TimeUnit.HOURS.toMillis(2))//两个小时
    }
    get.execute(object : JsonCallback<T>(type) {
        override fun onSuccess(response: Response<T>?) {
            if (response != null && response.isSuccessful) {
                it.resume(response.body())
            } else {
                it.resumeWithException(IllegalStateException("NetWork error"))
            }
        }

        override fun onCacheSuccess(response: Response<T>?) {
            if (response != null && response.isSuccessful) {
                it.resume(response.body())
            } else {
                it.resumeWithException(IllegalStateException("NetWork error"))
            }
        }

        override fun onError(response: Response<T>?) {
            super.onError(response)
            it.resumeWithException(IllegalStateException("NetWork error"))
        }
    })
}

相关文章

  • Kotlin 协程的简单使用

    Kotlin 协程的简单使用 1. 关于协程 协程(Coroutines)和线程(Threads)是两个完全不同的...

  • 协程的简单使用

    1、协程作用范围。 全局有效。 生命周期内有效。 1、基本使用。 开启同步协程。 输出: 123 开启异步协程。 ...

  • 协程的简单使用

  • 协程.md

    协程协程中使用suspend修饰方法,代表该方法可在协程中挂起。但并不是协程方法必须使用suspend修饰协程和线...

  • Kotlin协程一些概念理解

    协程的概念 协程就是 Kotlin 提供的一套线程封装的 API,使用协程可以让多线程之间的通信更加简单。总之一句...

  • XLua里使用协程

    在XLua里如何使用协程?有两种方式 使用Unity协程要想通过unity的StartCoroutine使用协程,...

  • 协程(三)IEnumerable、IEnumerator、for

    协程(一)基本使用协程(二)协程什么时候调用协程(三)IEnumerable、IEnumerator、foreac...

  • 协程(五)简单模拟协程

    协程(一)基本使用协程(二)协程什么时候调用协程(三)IEnumerable、IEnumerator、foreac...

  • 协程(一)基本使用

    协程(一)基本使用协程(二)协程什么时候调用协程(三)IEnumerable、IEnumerator、foreac...

  • 协程(六)有关优化

    协程(一)基本使用协程(二)协程什么时候调用协程(三)IEnumerable、IEnumerator、foreac...

网友评论

      本文标题:协程的简单使用

      本文链接:https://www.haomeiwen.com/subject/uzicfktx.html