js css html

Kotlin-Coroutines 中的async与await

2022-09-16  本文已影响0人  ZoranLee

Coroutines

官网说明

什么是协程?(摘自官网)

简单概括 :

协程的创建/启动

协程作用域(CoroutineScope)

class MyFragment: Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewLifecycleOwner.lifecycleScope.launch {
            val params = TextViewCompat.getTextMetricsParams(textView)
            val precomputedText = withContext(Dispatchers.Default) {
                PrecomputedTextCompat.create(longTextContent, params)
            }
            TextViewCompat.setPrecomputedText(textView, precomputedText)
        }
    }
}
 class MyViewModel: ViewModel() {
    init {
        viewModelScope.launch {
            // Coroutine that will be canceled when the ViewModel is cleared.
        }
    }
}
val user: LiveData<User> = liveData {
    val data = database.loadUser() // loadUser is a suspend function.
    emit(data)
}

异步、并发、并行

异步

并发

并行

并发就是一次处理很多事情,并行就是一次做很多事情

协程中的并发和并行

import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis

fun main(args: Array<String>) =
    runBlocking {
        val time = measureTimeMillis {
            val one = async { doSomethingUsefulOne() }
            val two = async { doSomethingUsefulTwo() }
            println("The answer is ${one.await()} ${two.await()}")
        }
        println("Completed in $time ms")
    }

suspend fun doSomethingUsefulTwo() :Int{
    delay(1000L)
    println("two")
    return  2
}

suspend fun doSomethingUsefulOne():Int {
    delay(1000L)
    println("one")
    return  1
}


one
two
The answer is 1 2
Completed in 1020 ms

并行

suspend fun doSomethingUsefulOne(): BigInteger = withContext(Dispatchers.Default) {
    measureTimedValue {
        println("in doSomethingUsefulOne")
        BigInteger(1500, Random()).nextProbablePrime()
    }
}.also {
    println("Prime calculation took ${it.duration} ms")
}.value
上一篇 下一篇

猜你喜欢

热点阅读