由于类型不匹配,无法在 Flow 中发出 Either.Left
Cannot Emit Either.Left in Flow because of type mismatch
这里我有一个函数可以获取一些数据。我使用 Either 将数据发送到 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>>
}
Flow 在 .map
应用后转换为 Flow<Right<Throwable, List<Stock>>>
,因此尝试将 Either.Left
类型的值发送到 Either.Right
流是错误的,因为 Either.Left
没有' 匹配 Either.Right
类型。将 Either.Right(it.stocks.toDomain())
转换为 Either<Throwable, List<Stock>>
应该可以解决这个问题。
这里我有一个函数可以获取一些数据。我使用 Either 将数据发送到 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>>
}
Flow 在 .map
应用后转换为 Flow<Right<Throwable, List<Stock>>>
,因此尝试将 Either.Left
类型的值发送到 Either.Right
流是错误的,因为 Either.Left
没有' 匹配 Either.Right
类型。将 Either.Right(it.stocks.toDomain())
转换为 Either<Throwable, List<Stock>>
应该可以解决这个问题。