Kotlin Coroutines

2018-11-07  本文已影响18人  lhl_012
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()
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读