0

Here I have i function that gets some data. I use Either for sending data to ViewModel.

sealed class Either<out L, out R> {
    /** * Represents the left side of [Either] class which by convention is a "Failure". */
    data class Left<out L>(val a: L) : Either<L, Nothing>()

    /** * Represents the right side of [Either] class which by convention is a "Success". */
    data class Right<out R>(val b: R) : Either<Nothing, R>()
}

How can I emit error data in catch block?

fun getStocksFlow(): Flow<Either<Throwable, List<Stock>>> = flow {
        val response = api.getStocks()
        emit(response)
    }
        .map {
            Either.Right(it.stocks.toDomain())
        }
        .flowOn(ioDispatcher)
        .catch { throwable ->
            emit(Either.Left(throwable)) //Here it shows Type mismatch, it needs Either.Right<List<Stock>>
        }
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Grigoriym
  • 328
  • 3
  • 7

1 Answers1

0

Flow transforms to Flow<Right<Throwable, List<Stock>>> after .map applying, so trying to emit value of Either.Left type to flow of Either.Right is wrong cause Either.Left doesn't match Either.Right type. Cast Either.Right(it.stocks.toDomain()) to Either<Throwable, List<Stock>> should fix that.

sibpf
  • 16