Created
August 20, 2020 18:29
-
-
Save ibrahimyilmaz/994ffbb9f094ffdea56db23e74d7a072 to your computer and use it in GitHub Desktop.
UseCase.kt
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
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