Kotlin协程

kotlin 1.3出来了,而协程(coroutines)也正式发布稳定版。虽然目前项目不是kotlin语言,但为了饭碗kotlin是必须的。而作为kotlin一个重要的内容,肯定要会使用的。
而协程(coroutine)要单独添加支持
在当前的项目添加依赖

dependencies {
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1'
}

在项目的最外层build.gradle添加依赖

buildscript {
    ext.kotlin_version = '1.3.0'
}
repository {
    jcenter()
}
第一个协程程序
 GlobalScope.launch { //在后台启动一个新的线程并继续(无阻塞)
        delay(1000L) //  delay 是一个特别的 挂起函数 ,它不会造成线程阻塞,挂起函数只能在协程中使用)
        println("World!") // 在延迟后打印输出
    }
    println("Hello,") // 主线程的协程将会继续等待
    Thread.sleep(2000L) // 阻塞主线程2秒钟来保证 JVM 存活

运行结果:

Hello,
World!
取消协程

其实GlobalScope.launch { }是有返回值的

public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job {
    val newContext = newCoroutineContext(context)
    val coroutine = if (start.isLazy)
        LazyStandaloneCoroutine(newContext, block) else
        StandaloneCoroutine(newContext, active = true)
    coroutine.start(start, coroutine, block)
    return coroutine
}

可以看到会返回一个Job对象,当然了,还可以看见会有构造参数,分别是协程的上下问和调度器。
具体含义参考:协程上下文与调度器
所以在启动协程的时候,我们可以声明一个Job对象来接收它。

 var job: Job? = null

  job = GlobalScope.launch { //在后台启动一个新的线程并继续(无阻塞)
  		...
  }

在需要取消的地方

  job?.cancel()
取消是协作的

有时候,我们在外面将协程取消来,而协程里面是个耗时的循环,为了保证协程里面代码不会在协程取消的时候还在执行。需要加载条件,保证协程里外状态一致性

  job = GlobalScope.launch { //在后台启动一个新的线程并继续(无阻塞)
            while (isActive){ //携程是否取消
                e(TAG, "Active")
            }
            try {
                repeat(1000){
                    i ->
                    Log.e(TAG,"I'm sleeping $i...")
                    delay(500L)
                }
            } finally {
                withContext(NonCancellable){
                    Log.e(TAG,"I'm running finally ")
                    delay(1000L)
                    Log.e(TAG,"And I've just delayed for 1 sec because I'm non-cancellable")
                }

            }
  }

而当协程因为异常而被取消时,我们可以在finally中作资源的释放操作

超时

设置协程的超时时长

val result = withTimeoutOrNull(1300L) {
    repeat(1000) { i ->
            println("I'm sleeping $i ...")
        delay(500L)
    }
    "Done" // 在它运行得到结果之前取消它
}
println("Result is $result")

运行结果:

I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
Result is null

如果直接使用withTimeout()而不是withTimeoutOrNull()会抛出TimeoutCancellationException异常

I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1300 ms
结合挂起函数
    //挂起函数
    suspend fun doSomethingOne(): Int {
        delay(1000L) //假设在这里做了一些有用的事
        return 22
    }

    suspend fun doSomethingTwo(): Int {
        delay(1000L) //假设在这里做了一些有用的事
        return 11
    }
按照默认顺序调用
  val TAG: String = javaClass.name

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //默认顺序调用
        runBlocking {//显示阻塞,相当于主协程
            val time = measureTimeMillis {
                val one = doSomethingOne()
                val two = doSomethingTwo()
                e(TAG, "the answer is ${one + two}")
            }
            e(TAG, "Completed in $time ms    " + Thread.currentThread().name)
        }
	}

运行结果:

the answer is 33
Completed in 2002 ms    main
使用async并发
        //使用async并发
        runBlocking {
            val time = measureTimeMillis {
                val one = GlobalScope.async{ doSomethingOne() }
                val two = GlobalScope.async{ doSomethingTwo() }
                e(TAG,"async the answer is ${one.await() + two.await()}" )
            }
            e(TAG,"async Completed in $time ms    " + Thread.currentThread().name)
        }

显示结果:

async the answer is 33
async Completed in 1013 ms    main

async概念:
async 就类似于 launch。它启动了一个单独的协程,这是一个轻量级的线程并与其它所有的协程一起并发的工作。不同之处在于 launch 返回一个 Job 并且不附带任何结果值,而 async 返回一个 Deferred —— 一个轻量级的非阻塞 future, 这代表了一个将会在稍后提供结果的 promise。你可以使用 .await() 在一个延期的值上得到它的最终结果, 但是 Deferred 也是一个 Job,所以如果需要的话,你可以取消它。

惰性启动async
        //惰性启动async  只有结果需要被await或者start调用,协程才会被启动
        runBlocking {
            val time = measureTimeMillis {
                val one = GlobalScope.async(start = CoroutineStart.LAZY){ doSomethingOne() }
                val two = GlobalScope.async(start = CoroutineStart.LAZY){ doSomethingTwo() }
                //执行一些计算
                one.start()
                two.start()
                e(TAG,"async lazy the answer is ${one.await() + two.await()}" )
            }
            e(TAG,"async lazy Completed in $time ms    " + Thread.currentThread().name)
        }

运行结果:

async lazy the answer is 33
async lazy Completed in 1026 ms    main
在协程外面调用async
    /**
     *  async风格的函数
     *  返回类型是 Deferred
     *  这些函数不是挂起函数,可以在任何地方被调用。并且是异步(并发)执行
     */
    fun someOneAsync() = GlobalScope.async{
        doSomethingOne()
    }

    fun someTwoAsync() = GlobalScope.async{
        doSomethingTwo()
    }

上面是async风格的函数,下面是调用

 //在协程的外面调用async,注意此时没有使用runBlocking
        val time = measureTimeMillis {
            //在协程外面启动异步执行
            val one = someOneAsync()
            val two = someTwoAsync()
            //但是等待结果必须调用其它的的挂起或者阻塞
            //当我们等待结果的时候,这里使用runBlocking{}来阻塞主线程
            runBlocking{
                e(TAG,"the answer is ${one.await() + two.await()}")
            }
        }
        e(TAG,"Completed in $time ms")

运行结果:

the answer is 33
Completed in 1014 ms
这种带有异步函数的编程风格仅供参考,因为这在其它编程语言中是一种受欢迎的风格。在 Kotlin 的协程中使用这种风格是强烈不推荐的
使用async的结构化并发
    /**
     * 结构话并发 如果concurrentSum() 内部发生错误,并且抛出来异常,所有在作用域中启动的协程都将被取消
     */
    suspend fun concurrentSum(): Int = coroutineScope{
        val one = GlobalScope.async{ doSomethingOne() }
        val two = GlobalScope.async{ doSomethingTwo() }
        one.await() + two.await()
    }

调用:

        //使用async的结构化并发
        runBlocking{
            val time = measureTimeMillis {
                e(TAG,"The answer is ${concurrentSum()}")
            }
            e(TAG,"Compled in $time ms")
        }

运行结果:

 The answer is 33
 Compled in 1013 ms
取消始终通过协程的层次结构来进行传递
fun main() = runBlocking<Unit> {
    try {
        failedConcurrentSum()
    } catch(e: ArithmeticException) {
        println("Computation failed with ArithmeticException")
    }
}

suspend fun failedConcurrentSum(): Int = coroutineScope {
    val one = async<Int> { 
        try {
            delay(Long.MAX_VALUE) // 模拟一个长时间的运算
            42
        } finally {
            println("First child was cancelled")
        }
    }
    val two = async<Int> { 
        println("Second child throws an exception")
        throw ArithmeticException()
    }
        one.await() + two.await()
}

运行结果:

Second child throws an exception
First child was cancelled
Computation failed with ArithmeticException

failedConcurrentSum()one.await() + two.await()在安卓里面写是不被允许的,会报错。因此就直接拷贝Java代码来。的注意观察运行结果调用的顺序,当一个async作用域中有一个子协程发生异常,另外的子协程也会被取消。

好了,这里记录一些kotlin协程的一些简单使用,想要熟练和深刻还得在项目中使用才行

参考:Kotlin文档-协程

你可能感兴趣的:(kotlin)