kotlin学习-Coroutines(协程)

协程,相似线程,非阻塞式编程(像同步编写同样),在用户态直接对线程进行管理,使用挂起当前上下文替代阻塞,从而能够复用被delay的线程,大量减小了线程资源浪费。java

基本使用:android

fun runAsync()= runBlocking {
    val time = measureTimeMillis {//系统函数统计时间
        val one = async { doSomethingUsefulOne() }//异步调用,返回结果
        val two = async { doSomethingUsefulTwo() }
        println("The answer is ${one.await() + two.await()}")//等待异步执行完成(wait调用会挂起当前线程)
    }
    println("Completed in $time ms")
}

//协程coroutines 调用方法须要suspend修饰
suspend fun doSomethingUsefulOne(): Int {
    delay(1000L) // pretend we are doing something useful here
    return 13
}

suspend fun doSomethingUsefulTwo(): Int {
    delay(1000L) // pretend we are doing something useful here, too
    return 29
}

 这里面没有使用异步+回调,直接像写同步代码同样,简洁编程

launch 返回Job可取消任务app

fun cancelCoroutine() = runBlocking {
    val startTime = System.currentTimeMillis()
    val job = launch(Dispatchers.Default) {
        var nextPrintTime = startTime
        var i = 0
        while (isActive) { // cancellable computation loop
            // print a message twice a second
            if (System.currentTimeMillis() >= nextPrintTime) {
                println("job: I'm sleeping ${i++} ...")
                nextPrintTime += 500L
            }
        }
    }
    delay(1300L) // delay a bit
    println("main: I'm tired of waiting!")
    job.cancelAndJoin() // cancels the job and waits for its completion
    println("main: Now I can quit.")
}

线程之间切换异步

fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
fun jumpCor(){//建立单线程coroutines
    newSingleThreadContext("Ctx1").use { ctx1 ->
        newSingleThreadContext("Ctx2").use { ctx2 ->
            runBlocking(ctx1) {
                log("Started in ctx1")
                withContext(ctx2) {
                    log("Working in ctx2")
                }
                log("Back to ctx1")
            }
        }
    }
}

 方法内建立Scopesocket

suspend fun showSomeData() = coroutineScope {
      val data = async(Dispatchers.IO) { // IO task  io线程调用操做
//          ... load some UI data for the Main thread ...
       }

    withContext(Dispatchers.Main){//UI task  UI更新
        val result = data.await()
//        display(result)
    }
}

 

协程上下文环境,CoroutineScope,CoroutineContextasync

每一个协程运行须要在指定Scope内才能使用协程相关方法delay,asyc,launch,建立CoroutineScope ,runBlocking函数内部会建立CoroutineScope,系统提供GlobalScope,MainScope等辅助类内部建立Scopeide

也能够经过CoroutineContext和Job建立本身的CoroutineScope函数

 

fun sampleCreateCorountine(){
    //create corountine scope
    //自定义CoroutineScope
    val coroutineContext = Dispatchers.Default
    val job = Job()
    val coroutineScope = CoroutineScope(coroutineContext + job)
    //使用scope
    coroutineScope.launch {

    }
    //建立全局Scope
    GlobalScope.launch (Dispatchers.Default+CoroutineName("global background thread")){

    }
    //建立主线程分发处理Scope
    MainScope().launch {

    }

}

 

类内部定义协程oop

1,直接继承CoroutineScope

class SomethingWithLifecycle : CoroutineScope {
    // 使用job来管理你的SomethingWithLifecycle的全部子协程
    private val job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    fun destory(){//退出取消
        job.cancel()
    }
}

2,直接使用已定义Scope

class CorMyActivity : AppCompatActivity(), CoroutineScope by MainScope() {

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

    /**
     * Note how coroutine builders are scoped: if activity is destroyed or any of the launched coroutines
    in this method throws an exception, then all nested coroutines are cancelled.
     */
    fun showSomeData() = launch {
        // <- extension on current activity, launched in the main thread
        // ... here we can use suspending functions or coroutine builders with other dispatchers
//        draw(data) // draw in the main thread
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }

}

 

 

Dispatchers,协程分发器:

fun dispatchTask()= runBlocking<Unit> {
    // it inherits the context (and thus dispatcher) from the CoroutineScope that it is being launched from.
        launch { // context of the parent, main runBlocking coroutine
            println("main runBlocking      : I'm working in thread ${Thread.currentThread().name}")
        }
    //执行coroutine是在调用者的线程,可是当在coroutine中第一个挂起以后,后面所在的线程将彻底取决于
    // 调用挂起方法的线程(如delay通常是由kotlinx.coroutines.DefaultExecutor中的线程调用)
    //Unconfined在挂起后在delay的调用线程DefaultExecutor执行
        launch(context = Dispatchers.Unconfined) { // not confined -- will work with main thread
            println("Unconfined            : I'm working in thread ${Thread.currentThread().name}")
        }
    // coroutines are launched in GlobalScope,uses shared background pool of threads
    //uses the same dispatcher as GlobalScope.launch
  //Dispatchers.Default 处理cup密集型任务,线程数为cpu内核数,最少为2,Dispatchers.IO 处理阻塞性IO,socket密集度任务,数量随任务多少变化,默认最大数量64 launch(context = Dispatchers.Default) { // will get dispatched to DefaultDispatcher println("Default : I'm working in thread ${Thread.currentThread().name}") } //creates a thread for the coroutine to run launch(newSingleThreadContext("MyOwnThread")) { // will get its own new thread println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}") } }

 

协程结合Architecture ViewModel

class NewsViewModel: ViewModel() {

    private val mApi:WebServer
    init {
        mApi = WebServer()
    }

    val dataNews: MutableLiveData<DataResource<NewsDataRsp>> by lazy {
//        MutableLiveData<DataResource<NewsDataRsp>>().also {
//            loadNewsData(minId=null)
//        }
        MutableLiveData<DataResource<NewsDataRsp>>()
    }

     fun loadNewsData(pageIndex:Int =1,countItem:Int = 20,minId:String?=null){
        runCoroutine(dataNews){
            val mp = mutableMapOf("encode" to "ywjh","source" to "app","sys" to "android","banner" to "banner",
                    "limit" to countItem.toString(),"version" to "7002000")
            if(pageIndex>1 && false==minId.isNullOrEmpty()){
                mp.put("min_id",minId)
            }
            val response = mApi.commonDataSourceApi.getNewsData(mp).execute()
            return@runCoroutine response.body()!!
        }
    }

     fun fetchNews(pageIndex:Int =1,countItem:Int = 20,minId:String){
         val mp = mutableMapOf("encode" to "ywjh","source" to "app","sys" to "android","banner" to "banner",
                 "limit" to countItem.toString(),"version" to "7002000")
         if(pageIndex>1 && false==minId.isNullOrEmpty()){
             mp.put("min_id",minId)
         }

         val cor = CoroutineScope(Dispatchers.IO)
         cor.launch {
             try {
                 val response = mApi.commonDataSourceApi.getNewsData(mp).execute()
                 dataNews.postValue(DataResource(DataResource.Status.COMPLETED, response.body(), null))
             } catch (exception: Exception) {
                 dataNews.postValue(DataResource(DataResource.Status.COMPLETED, null, exception))
             }
         }
    }

    suspend fun simpleGetData(pageIndex:Int =1,countItem:Int = 20,minId:String) = withContext(Dispatchers.IO) {
        val mp = mutableMapOf("encode" to "ywjh","source" to "app","sys" to "android","banner" to "banner",
                "limit" to countItem.toString(),"version" to "7002000")
        if(pageIndex>1 && false==minId.isNullOrEmpty()){
            mp.put("min_id",minId)
        }

        try {
            val response = mApi.commonDataSourceApi.getNewsData(mp).execute()
            dataNews.postValue(DataResource(DataResource.Status.COMPLETED, response.body(), null))
        } catch (exception: Exception) {
            dataNews.postValue(DataResource(DataResource.Status.COMPLETED, null, exception))
        }
    }

    private fun <T> runCoroutine(correspondenceLiveData: MutableLiveData<DataResource<T>>, block: suspend () -> T) {
        correspondenceLiveData.value = DataResource(DataResource.Status.LOADING, null, null)

        GlobalScope.launch(Dispatchers.IO) {
            try {
                val result = block()
                correspondenceLiveData.postValue(DataResource(DataResource.Status.COMPLETED, result, null))
            } catch (exception: Exception) {
//                val error = ErrorConverter.convertError(exception)
                correspondenceLiveData.postValue(DataResource(DataResource.Status.COMPLETED, null, exception))
            }
        }
    }

}
相关文章
相关标签/搜索