Last active
October 4, 2020 19:56
-
-
Save Kiolk/2dbff01233f6ad74e70458053b352a08 to your computer and use it in GitHub Desktop.
Coroutines Example: Base UseCase with coroutine
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
abstract class BaseUseCase<in Param, out Type> where Type : Any { | |
abstract suspend fun run(param: Param): Either<Failure, Type> | |
open val dispatcher: CoroutineDispatcher = Dispatchers.Main | |
open operator fun invoke( | |
scope: CoroutineScope, | |
param: Param, | |
result: (Either<Failure, Type>) -> Unit = {} | |
): Job { | |
val backgroundJob = scope.async(dispatcher) { run(param) } | |
return scope.launch(Dispatchers.Main) { result.invoke(backgroundJob.await()) } | |
} | |
open operator fun invoke( | |
viewModel: BaseViewModel, | |
param: Param, | |
result: (Either<Failure, Type>) -> Unit = {} | |
): Job { | |
viewModel.showProgress() | |
val backgroundJob = viewModel.viewModelScope.async(dispatcher) { run(param) } | |
return viewModel.viewModelScope.launch(Dispatchers.Main) { | |
val executionResult = backgroundJob.await() | |
viewModel.hideProgress() | |
result.invoke(executionResult) | |
} | |
} | |
protected fun onWrapException(exception: Exception): Failure { | |
return try { | |
when (exception) { | |
is UnknownHostException -> Failure.NetworkFailureL(exception) | |
is ConnectException -> Failure.NetworkFailureL(exception) | |
is HttpException -> HttpExceptionHandler.onHandleException(exception) | |
else -> Failure.UnknownFailure(exception) | |
} | |
} catch (exception: Exception) { | |
Failure.UnknownFailure(exception) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment