Skip to content

Question about loading  #2

@fabiosaracino

Description

@fabiosaracino

Dear author,
I'm reading the book and putting the examples into practice. I was wondering how I can encapsulate the loading status within the ApiResult class used within the UseCase class to output the success (or failure) of I/O operations.
I cannot find the right position to put the emit(ApiResult.Loading).
Thank you in advance!

This is the ApiResult class:

sealed class ApiResult<out T: Any> {
    data class Success<out T: Any>(val data: T): ApiResult<T>()
    class Error(val exception: UseCaseException): ApiResult<Nothing>()
    data object Loading: ApiResult<Nothing>()
}

This is the UseCase class:

abstract class UseCase<T: UseCase.Request, R: UseCase.Response>
    (private val dispatcher: CoroutineDispatcher) {

    fun execute(input: T): Flow<ApiResult<R>> =
        executeData(input)
            .map {
                ApiResult.Success(it) as ApiResult<R>
            }
            .flowOn(dispatcher)
            .catch {
                emit(ApiResult.Error(UseCaseException.createFromThrowable(it)) as ApiResult<R>)
            }

    protected abstract fun executeData(input: T): Flow<R>

    interface Request
    interface Response
}

and this is ChecUserEmaiUseCase class

class CheckUserEmailUseCase(
    dispatcher: CoroutineDispatcher,
    private val userRepository: UserRepository
): UseCase<CheckUserEmailUseCase.Request, CheckUserEmailUseCase.Response>(dispatcher) {

    override fun executeData(input: Request): Flow<Response> =
        userRepository.checkEmail(input.email)
            .map {
                Response(it)
            }

    data class Request(val email: String): UseCase.Request
    data class Response(val found: Boolean): UseCase.Response
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions