美文网首页
安卓协程那些事2-协程上下文Coroutine Context

安卓协程那些事2-协程上下文Coroutine Context

作者: itBox | 来源:发表于2022-06-29 14:16 被阅读0次

    本文介绍什么是协程上下文,及如何利用协程上下文

    先看一段代码

    package com.android.coroutineTest
    import ...
    class MainActivity : AppCompatActivity() {
        GlobalScope.launch(Dispatchers.IO){
                Log.d(TAG, "Starting coroutine in thread ${Thread.currentThread().name}")
                val answer = doNetReq()
                withContext(Dispatchers.Main){
                    Log.d(TAG, "Setting text in thread ${Thread.currentThread().name}")
                    binding.btnTestDownFromTFCard.text = answer
                }
            }
    //suspend 必须加
    private suspend fun doNetReq(): String {
            delay(3000L)
            return "result is cool."
        }
    

    以上代码功能为在主线程修改Button的文字,使用 withContext 配合 Dispatchers.Main 实现。

    delay 是 suspend 方法

    suspend 方法只能在 协程中使用,且内调用 suspend 方法的方法也必须是 suspend。(有点绕)

    Dispatchers 是什么?

    源码注释:The CoroutineDispatcher that is designed for offloading blocking IO tasks to a shared pool of threads.

    Dispatchers 属性介绍
    Dispatchers.IO 操作数据
    Dispatchers.Main 主线程(UI线程)
    Dispatchers.Default 用于CPU计算任务

    区别:

    The difference is that Dispatchers.Default is limited to the number of CPU cores (with a minimum of 2) so only N (where N == cpu cores) tasks can run in parallel in this dispatcher.
    On the IO dispatcher there are by default 64 threads, so there could be up to 64 parallel tasks running on that dispatcher.
    The idea is that the IO dispatcher spends a lot of time waiting (IO blocked), while the Default dispatcher is intended for CPU intensive tasks, where there is little or no sleep.

    协程使用步骤

    添加依赖

    implementation  'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0'
    

    获取当前线程名

    Thread.currentThread().name

    关于 delay

    delay是一个顶级函数,由于它被suspend修饰,所以只能用在协程或者被其他suspend函数修饰,它的功能为

    delay( 1000L )

    将当前协程延迟一个给定时间,但是不会阻塞当前线程 并且它也是可以被取消的

    suspend 方法

    suspend使用案例
    https://www.jianshu.com/p/0eea02e7bc29

    如果这篇文章有帮助到你,请帮忙点点赞,感谢

    相关文章

      网友评论

          本文标题:安卓协程那些事2-协程上下文Coroutine Context

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