Skip to content

Instantly share code, notes, and snippets.

@mayojava
Created October 26, 2018 07:59
Show Gist options
  • Save mayojava/103d5c146ab7608d400055241f052c40 to your computer and use it in GitHub Desktop.
Save mayojava/103d5c146ab7608d400055241f052c40 to your computer and use it in GitHub Desktop.
Corotuine Observer
class CoroutineObserver: LifecycleObserver, CoroutineScope {
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Default
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
job = Job()
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
job.cancel()
}
}
class TestActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycle.addObserver(CoroutineObserver())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment