美文网首页
Kotlin Coroutines

Kotlin Coroutines

作者: lhl_012 | 来源:发表于2018-11-07 14:30 被阅读18次
    import android.arch.lifecycle.Lifecycle
    import android.arch.lifecycle.LifecycleObserver
    import android.arch.lifecycle.LifecycleOwner
    import android.arch.lifecycle.OnLifecycleEvent
    import kotlinx.coroutines.*
    
    fun <T> LifecycleOwner.load(loadFunction: () -> T): Deferred<T> {
        val deferred = GlobalScope.async(context = Dispatchers.IO, start = CoroutineStart.LAZY) { loadFunction() }
        lifecycle.addObserver(CoroutineLifecycleListener(deferred))
        return deferred
    }
    
    infix fun <T> Deferred<T>.then(uiFunction: (T) -> Unit) {
        GlobalScope.launch(context = Dispatchers.Main) { uiFunction(this@then.await()) }
    }
    
    class CoroutineLifecycleListener(private val deferred: Deferred<*>) : LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun cancelCoroutine() {
            if (!deferred.isCancelled) {
                deferred.cancel()
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Kotlin Coroutines

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