Skip to content

Instantly share code, notes, and snippets.

@liamkernighan
Created February 26, 2020 10:09
Show Gist options
  • Save liamkernighan/1e781413c656a105d2eb7752bc47e72b to your computer and use it in GitHub Desktop.
Save liamkernighan/1e781413c656a105d2eb7752bc47e72b to your computer and use it in GitHub Desktop.
Coroutine exception handler
package com.nasladdin.partner.boilerplate
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.*
import java.lang.Exception
import kotlin.coroutines.CoroutineContext
@Suppress("unused")
abstract class StoreBase(private val thisLifecycle: Lifecycle, private val context: CoroutineContext = Dispatchers.IO): CoroutineScope, LifecycleObserver, LifecycleOwner {
init {
@Suppress("LeakingThis")
thisLifecycle.addObserver(this)
}
private val handler = CoroutineExceptionHandler { _, throwable ->
Log.d("ERROR", "Coroutine has thrown an exception")
Exception(throwable).printStackTrace()
throw throwable
}
private val compositeJob = Job()
override val coroutineContext: CoroutineContext
get() = context + compositeJob + handler
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
compositeJob.cancel()
thisLifecycle.removeObserver(this)
}
override fun getLifecycle(): Lifecycle {
return thisLifecycle
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment