问题描述
这里我有获取一些数据的函数。我使用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<Right<Throwable,List<Stock>>>
后流转换为 .map
,因此尝试将 Either.Left
类型的值发送到 Either.Right
流是错误的,因为 Either.Left
不会匹配 Either.Right
类型。将 Either.Right(it.stocks.toDomain())
转换为 Either<Throwable,List<Stock>>
应该可以解决这个问题。