Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gpeal
Created June 1, 2019 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpeal/a9e6b802ab2d5846ae44bee173f34c6c to your computer and use it in GitHub Desktop.
Save gpeal/a9e6b802ab2d5846ae44bee173f34c6c to your computer and use it in GitHub Desktop.
fun <T : Any?> execute(
fn: suspend () -> T,
onError: (suspend (Exception) -> Unit)? = null,
dispatcher: CoroutineDispatcher = Dispatchers.Default,
reducer: S.(Async<T>) -> S
) {
uiScope.launch(dispatcher) {
setState { reducer(Loading()) }
try {
val result = fn()
setState { reducer(Success(result)) }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
onError?.invoke(e)
setState { reducer(Fail(e)) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment