Emitting the data via FlowCollector instead of emit() does not work

91 Views Asked by At

I have a BaseUseCase class which orchestrates the states this way:

abstract class BaseUseCase<T, in P: UseCaseParameters> {

    protected abstract suspend fun FlowCollector<Result<T>>.run(params: P)

    operator fun invoke(params: P) =
        flow {
            emit(State.Loading)
            run(params)
            emit(State.Loaded)
        }.flowOn(Dispatchers.IO)
}

The expected output for Flow.collect{} scope is :

State.Loading
State.Success / State.Error // where I get the success or error data
State.Loaded

It was working fine for API calls etc. so far. Now, I have a specific implementation where I read the JSON file from assets and emit it into the flow. For this scenario, It is only emitting Loading and Loaded states.

here is the rest of the implementation :

ViewModel:

private fun getAllCards() {
        viewModelScope.launch {
            getAllCardsUseCase(None()).collect {
                val printData: String = when (it) {
                    is State -> it.toString()
                    is Failure -> it.errorData.message.toString()
                    is Success -> {
                        it.successData.cardList.first().name }
                }
                Timber.d("ALL CARDS RESPONSE = $printData")
            }
        }
    }

UseCase :

class GetAllCardsUseCase<T : ViewEntity> @Inject constructor(
    private val mapper: @JvmSuppressWildcards Mapper<ArrayList<Card>, T>,
    private val cardRepository: CardRepository
) : BaseUseCase<T, None>() {
    override suspend fun FlowCollector<Result<T>>.run(params: None) {
        cardRepository.getCardList(mapper = mapper)
    }
}

Repository :

override suspend fun <T : ViewEntity> getCardList(mapper: Mapper<ArrayList<Card>, T>): Result<T> =
    readCardListFromFile()?.let {
        Success(successData = mapper.convert(it))
    } ?: run {
        Failure(errorData = ParsingError())
    }

The JSON data is being retrieved and mapped into the model successfully in let{} block.

getCardList() returns the Success state as expected, but it is never being emitted. What am I missing?

1

There are 1 best solutions below

1
On BEST ANSWER

Please try adding emit() to the overriden run() function of the GetAllCardsUseCase:

override suspend fun FlowCollector<Result<T>>.run(params: None) {
    emit(cardRepository.getCardList(mapper = mapper))
}