Skip to content

Instantly share code, notes, and snippets.

@ibrahimyilmaz
Created August 20, 2020 18:29
Show Gist options
  • Save ibrahimyilmaz/994ffbb9f094ffdea56db23e74d7a072 to your computer and use it in GitHub Desktop.
Save ibrahimyilmaz/994ffbb9f094ffdea56db23e74d7a072 to your computer and use it in GitHub Desktop.
UseCase.kt
inline fun <T> ViewModel.useCase(
noinline call: suspend () -> Result<T>,
noinline onError: (suspend (exception: Throwable) -> Unit)? = null,
noinline onSuccess: (suspend (data: T) -> Unit)? = null
) {
flow {
when (val response = call()) {
is Result.Success -> emit(response.data)
is Result.Error -> throw response.exception
}
}.onEach {
onSuccess?.invoke(it)
}.catch { throwable ->
onError?.invoke(throwable)
}.launchIn(viewModelScope)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment