althaf
09/21/2022, 4:41 PMjava.lang.IllegalArgumentException: Flow context cannot contain job in it. Had [SupervisorJobImpl{Active}@7b4ca1f, <http://Dispatchers.IO|Dispatchers.IO>]
interface UseCaseScope : CoroutineScope {
override val coroutineContext: CoroutineContext
get() = SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>
}
FlowUsecase : UseCaseScope {
<snip>
}
The intention here is to cancel the coroutine context when we business logic need to cancel it. So that i can call coroutineContext.cancel()
class LoginUseCase(private val authRepository: AuthRepository) : FlowUseCase<LoginRequest, Boolean>() {
override fun execute(parameter: LoginRequest): Flow<Result<Boolean>> =
flow {
authRepository.login(parameter.username, parameter.password).collect { response ->
this.defaultResultHandler(onSuccess = {
emit(Result.success(true))
}, response)
}
}.flowOn(coroutineContext)
override fun cancel() {
coroutineContext.cancel()
}
}
^^^ will cause app the crashCiaran Sloan
09/21/2022, 5:21 PMFlow context cannot contain job in it
. Therefor you should not be passing a job to the .flowOn
operator. Instead pass the dispatcherCiaran Sloan
09/21/2022, 5:23 PMexecute
flowCiaran Sloan
09/21/2022, 5:27 PMLoginUseCase
you would have:
class MyClass(
private val loginUseCase: LoginUseCase
) {
fun doWork() {
scope.launch {
loginUseCase.execute(...)
.collect()
}
}
fun cleanup() {
scope.cancel() //
}
}
althaf
09/27/2022, 3:28 AM