'Cannot Emit Either.Left in Flow because of type mismatch

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>>
        }


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sibpf