Skip to content

Instantly share code, notes, and snippets.

@MkhytarMkhoian
Last active May 16, 2024 12:49
Show Gist options
  • Save MkhytarMkhoian/7a2fbf1603e2c78f18d277af44181000 to your computer and use it in GitHub Desktop.
Save MkhytarMkhoian/7a2fbf1603e2c78f18d277af44181000 to your computer and use it in GitHub Desktop.
suspend inline fun <R> ViewModel.executeUseCase(block: () -> R): Result<R> =
viewModelScope.executeUseCase(block)
suspend inline fun <R> CoroutineScope.executeUseCase(block: () -> R): Result<R> {
return runSuspendCatching(block)
.onFailure { e ->
coroutineScope { coroutineContext }.let { coroutineContext ->
coroutineContext[CoroutineExceptionHandler]?.run {
handleException(coroutineContext, e)
}
}
}
}
inline fun <R> runSuspendCatching(block: () -> R): Result<R> {
return try {
Result.success(block())
} catch (cancellationException: CancellationException) {
throw cancellationException
} catch (e: Throwable) {
Result.failure(e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment