alGhul7
alGhul7

Reputation: 133

Base UseCase with coroutines kotlin

I want to have a BaseUseCase class by following:

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.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

abstract class SimpleBaseUseCase<out ResultType, in Params> where ResultType : Any {
    private val backgroundDispatcher: CoroutineDispatcher = Dispatchers.IO
    private val uiDispatcher: CoroutineDispatcher = Dispatchers.Main

protected 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")
    }
}

Upvotes: 0

Views: 204

Answers (0)

Related Questions