Skip to content

Instantly share code, notes, and snippets.

@Kiolk
Last active October 4, 2020 19:56
Show Gist options
  • Save Kiolk/2dbff01233f6ad74e70458053b352a08 to your computer and use it in GitHub Desktop.
Save Kiolk/2dbff01233f6ad74e70458053b352a08 to your computer and use it in GitHub Desktop.
Coroutines Example: Base UseCase with coroutine
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