Forked from ErikHellman/kotlin_coroutine_android_loader.kt
Created
January 9, 2018 10:18
-
-
Save suclike/29d9b1094f1a33e867e8b2f0c052524e to your computer and use it in GitHub Desktop.
Kotlin Coroutine Android Loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| internal class CoroutineLifecycleListener(private val deferred: Deferred<*>) : LifecycleObserver { | |
| @OnLifecycleEvent(Lifecycle.Event.ON_STOP) | |
| fun cancelCoroutine() { | |
| deferred.cancel() | |
| } | |
| } | |
| internal var POOL = newFixedThreadPoolContext(2, "loader") | |
| fun <T> LifecycleOwner.load(loader: () -> T): Deferred<T> { | |
| val deferred = async(context = POOL, start = CoroutineStart.LAZY) { loader() } | |
| val coroutineLifecycleListener = CoroutineLifecycleListener(deferred) | |
| lifecycle.addObserver(coroutineLifecycleListener) | |
| return deferred | |
| } | |
| infix fun <T> Deferred<T>.then(block: (T) -> Unit) = async(context = UI) { block([email protected]()) } | |
| class MyActivity : AppCompatActivity() { | |
| lateinit var text: String | |
| override fun onCreate(savedInstanceState: Bundle?) { | |
| super.onCreate(savedInstanceState) | |
| load { | |
| "This is an expensive loading..." | |
| } then { | |
| text = it | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment