Created
June 2, 2022 16:19
-
-
Save rommansabbir/1ebaa0b5a918ef33dba9a4db220456a2 to your computer and use it in GitHub Desktop.
Use UseCase to execute operation by following SRP.
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
/** | |
* UseCase is designed to execute a given operation by following | |
* Single Responsibility Design Principle. | |
*/ | |
abstract class UseCaseV2<ReturnType, in Params> where ReturnType : Any { | |
/** | |
* Abstract API that should be implemented by the respective child to execute the operation. | |
* | |
* @param params [Params] | |
* | |
* @return [AppResult]<[ReturnType]> | |
*/ | |
abstract suspend fun run(params: Params): AppResult<ReturnType> | |
/** | |
* Client access point to execute the [UseCaseV2]. | |
* | |
* Can provide [CoroutineDispatcher] to execute the [UseCaseV2] | |
* with the context of provided [CoroutineDispatcher]. | |
* | |
* Also, client can define that if this [UseCaseV2] is performing | |
* CPU intensive work or not. If yes, use [Dispatchers.Default] | |
* else accept the execution as IO Operation and use [Dispatchers.IO]. | |
* | |
* Note: [isCPUIntensiveWork] will work only if [useCustomDispatcher] is null. | |
* | |
* @param params [Params] to be passed. | |
* @param useCustomDispatcher to execute [UseCaseV2] with provided [CoroutineDispatcher] context. | |
* @param isCPUIntensiveWork to execute [UseCaseV2] with [Dispatchers.Default] if true else [Dispatchers.IO] | |
* | |
* @return [AppResult]<[ReturnType]> | |
*/ | |
suspend operator fun invoke( | |
params: Params, | |
useCustomDispatcher: CoroutineDispatcher? = null, | |
isCPUIntensiveWork: Boolean = false | |
): AppResult<ReturnType> { | |
val dispatcher = useCustomDispatcher | |
?: if (isCPUIntensiveWork) | |
Dispatchers.Default | |
else | |
Dispatchers.IO | |
return withContext(dispatcher) { run(params) } | |
} | |
} | |
interface AuthRepo { | |
fun login(username: String, password: String): AppResult<String> | |
} | |
class AuthRepoImpl() : AuthRepo { | |
override fun login(username: String, password: String): AppResult<String> { | |
//Assume that we are doing some kind of network operations here. | |
return AppResult.Success("Login Success.") | |
} | |
} | |
class LoginUseCase(private val repo: AuthRepo) : UseCaseV2<String, Pair<String, String>>() { | |
override suspend fun run(params: Pair<String, String>): AppResult<String> = | |
repo.login(params.first, params.second) | |
} | |
class AuthViewModel() : ViewModel() { | |
private val loginUseCase = LoginUseCase(AuthRepoImpl()) | |
suspend fun login(username: String, password: String) = loginUseCase( | |
Pair(username, password), null, false | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment