Kotlin Coroutines

import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.*

fun  LifecycleOwner.load(loadFunction: () -> T): Deferred {
    val deferred = GlobalScope.async(context = Dispatchers.IO, start = CoroutineStart.LAZY) { loadFunction() }
    lifecycle.addObserver(CoroutineLifecycleListener(deferred))
    return deferred
}

infix fun  Deferred.then(uiFunction: (T) -> Unit) {
    GlobalScope.launch(context = Dispatchers.Main) { uiFunction([email protected]()) }
}

class CoroutineLifecycleListener(private val deferred: Deferred<*>) : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun cancelCoroutine() {
        if (!deferred.isCancelled) {
            deferred.cancel()
        }
    }
}

你可能感兴趣的:(Kotlin Coroutines)