Created
February 26, 2020 10:09
-
-
Save liamkernighan/1e781413c656a105d2eb7752bc47e72b to your computer and use it in GitHub Desktop.
Coroutine exception handler
This file contains 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
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