Skip to content

Instantly share code, notes, and snippets.

@gorrotowi
Created March 31, 2022 22:33
Show Gist options
  • Save gorrotowi/4ecdf265e8c456d97ed8c551d1f1c519 to your computer and use it in GitHub Desktop.
Save gorrotowi/4ecdf265e8c456d97ed8c551d1f1c519 to your computer and use it in GitHub Desktop.
ViewModel with a function which handle the coroutine exception
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.flux.mobile.utils.loge
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
open class AwesomeViewModel(application: Application) : AndroidViewModel(application) {
private fun errorHandler(caughtError: (err: Throwable) -> Unit) =
CoroutineExceptionHandler { coroutineContext, throwable ->
loge("Coroutine Exception Handler")
loge("Coroutine Context -> $coroutineContext")
loge(msg = "Cause", thr = throwable)
caughtError(throwable)
}
fun executeCoroutine(
block: suspend CoroutineScope.() -> Unit,
errorBlock: (Throwable) -> Unit = {}
): Job {
val handler = errorHandler(errorBlock)
return viewModelScope.launch(handler) { block() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment