Created
September 26, 2018 13:53
-
-
Save diefferson/b41ed1d12fd95a7f3a67178fd321bc40 to your computer and use it in GitHub Desktop.
Use Case with Coroutines
This file contains 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 for a UseCase that returns an instance of a [T]. | |
*/ | |
abstract class UseCase<T, in Params> internal constructor( | |
private val postExecutionContext:CoroutineContext, | |
private val logException: LogException) : CoroutineScope { | |
private val executionJob: Job by lazy { Job() } | |
override val coroutineContext: CoroutineContext by lazy { | |
Dispatchers.IO + executionJob | |
} | |
/** | |
* Builds a [T] which will be used when the current callback is executed. | |
*/ | |
internal abstract suspend fun buildUseCaseObservable(params: Params): T | |
/** | |
* Executes the current use case. | |
*/ | |
fun execute(params: Params, | |
onError: (e: Throwable) -> Unit = {}, | |
onSuccess: (T) -> Unit = {}) { | |
launch{ | |
try { | |
val response = buildUseCaseObservable(params) | |
withContext(postExecutionContext) { | |
onSuccess(response) | |
} | |
} catch (e: Exception) { | |
withContext(postExecutionContext) { | |
logException.logException(e) | |
onError(e) | |
} | |
}catch (e: OutOfMemoryError){ | |
onError(KnownException(KnownError.OUT_OF_MEMORY_ERROR, e.message?:"")) | |
} | |
} | |
} | |
/** | |
* Dispose execution | |
*/ | |
fun dispose() { | |
executionJob.cancel() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment