Commit 773b5a17 authored by Geoffrey Métais's avatar Geoffrey Métais

CoroutineScope helper for LifecycleOwner classes

parent fe9a5792
......@@ -30,6 +30,9 @@ dependencies {
api "com.android.support:appcompat-v7:$rootProject.ext.appCompatVersion"
api "com.android.support:support-tv-provider:$rootProject.ext.appCompatVersion"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.ext.kotlinx_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.ext.kotlinx_version"
testImplementation "junit:junit:$rootProject.ext.junitVersion"
androidTestImplementation "com.android.support.test:runner:$rootProject.ext.supportTest"
......
package org.videolan.tools
import android.arch.lifecycle.GenericLifecycleObserver
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleOwner
import kotlinx.coroutines.experimental.CoroutineScope
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.android.Main
fun LifecycleOwner.createJob(cancelEvent: Lifecycle.Event = Lifecycle.Event.ON_STOP): Job = Job().also { job ->
lifecycle.addObserver(object : GenericLifecycleObserver {
override fun onStateChanged(source: LifecycleOwner?, event: Lifecycle.Event) {
if (event == cancelEvent) {
lifecycle.removeObserver(this)
job.cancel()
}
}
})
}
private val lifecycleCoroutineScopes = mutableMapOf<Lifecycle, CoroutineScope>()
val LifecycleOwner.coroutineScope: CoroutineScope
get() = lifecycleCoroutineScopes[lifecycle] ?: createJob().let {
val newScope = CoroutineScope(it + Dispatchers.Main.immediate)
lifecycleCoroutineScopes[lifecycle] = newScope
it.invokeOnCompletion { _ -> lifecycleCoroutineScopes -= lifecycle }
newScope
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment