如何解决由于类型不匹配,无法在 Flow 中发射任何一个
这里我有获取一些数据的函数。我使用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>>
应该可以解决这个问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。