I want to have a BaseUseCase class by following:
- Must allow to indicate the parameters.
- Must run the work itself in a background thread (that would be the doWork method).
- Must return the value in the main thread.
I want to return a value instead of returning it through a callback because I want the function that calls the usecase to be able to return the value directly once the usecase is finished.
I have the following approach, but I do not know if it is correct. I am using twice the @withContext, so I do not konw if it can be improved. Can you help me?
Current code:
import kotlinx.coroutines.CoroutineDispatcherimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextabstract class SimpleBaseUseCase<out ResultType, in Params> where ResultType : Any { private val backgroundDispatcher: CoroutineDispatcher = Dispatchers.IO private val uiDispatcher: CoroutineDispatcher = Dispatchers.Mainprotected abstract suspend fun doWork(params: Params): Result<ResultType>/** * @param params input data for the background job * @return the type of data indicated in @ResultType generic wrapped in a Result object. */open suspend operator fun invoke(params: Params): Result<ResultType> = withContext(uiDispatcher) { withContext(backgroundDispatcher) { doWork(params) }}
}
And, the caller would be:
class CustomHandler { //... suspend fun methodThatCallsUseCase: Result<String> { return useCase("paramExample") }}