【问题标题】:Cannot Emit Either.Left in Flow because of type mismatch由于类型不匹配,无法在 Flow 中发出 Either.Left
【发布时间】:2021-09-04 01:17:20
【问题描述】:

这里我有 i 函数来获取一些数据。我使用 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>>
        }

【问题讨论】:

    标签: android kotlin flow either


    【解决方案1】:

    在应用.map 之后,流转换为Flow&lt;Right&lt;Throwable, List&lt;Stock&gt;&gt;&gt;,因此尝试将Either.Left 类型的值发送到Either.Right 的流是错误的,因为Either.LeftEither.Right 类型不匹配。将Either.Right(it.stocks.toDomain()) 转换为Either&lt;Throwable, List&lt;Stock&gt;&gt; 应该可以解决这个问题。

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 2021-10-31
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多