Created
March 31, 2022 22:33
-
-
Save gorrotowi/4ecdf265e8c456d97ed8c551d1f1c519 to your computer and use it in GitHub Desktop.
ViewModel with a function which handle the coroutine exception
This file contains hidden or 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
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