由于类型不匹配,无法在流中发出任一.Left



这里有一个获取一些数据的函数。我使用"任一"将数据发送到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>()
}

如何在catch块中发出错误数据?

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

流在应用.map后转换为Flow<Right<Throwable, List<Stock>>>,因此尝试将Either.Left类型的值发射到Either.Right的流是错误的,因为Either.LeftEither.Right类型不匹配。将Either.Right(it.stocks.toDomain())强制转换为Either<Throwable, List<Stock>>应该可以解决此问题。

最新更新