4

我有一个 Dao 类,它以流的形式返回 Car 对象列表。

@Query("SELECT * FROM Car")
fun getAllCars(): Flow<List<Car>>

在我的存储库中,我可以按如下方式使用这个 Dao

fun getAllCars(): Flow<List<Car>>
//Implementation
override fun getAllCars() = carDao.getAllCars()

我可以flow在视图模型中观察到这一点,一切正常,生活也很好。

现在,在阅读了Developer Android 网站上关于

包含有关加载此数据的数据和状态的通用类。

我受到了启发,所以我在这里又读了一篇关于开设 Result 课程的文章。

所以,我对存储库做了一些更改,但我无法解决它们。

错误:


suspend fun getSomeData(): Flow<Result<List<Car>>> {
        carDao.getAllCars().collect {
            if (it.isNotEmpty()) {
                return flowOf(Result.Success(it))  //<-- Here I am getting error from IDE
            }
            else {
                val throwable = Throwable()
                return flowOf(Result.Failure<List<Car>>(throwable)) //<-- Here I am getting error from IDE
            }
        }
    }

错误是Return is not allowed hereChange to 'return@Collect'

我想要实现的是:

// At view model side
viewmodelScope.launch {

    repo.getSomeData().collect {
      if (it == Result.Success) {
        //Show data
      }
      else {
        //Show empty screen
      }

    }
}

我执行 Result 的方法是错误的吗?我无法弄清楚出了什么问题。为什么我不能只从流中返回流

4

2 回答 2

3

如果你想使用 Result,你应该返回 Result <YourClass>。它看起来像这样:

        suspend fun getSomeData(): Result<Flow<List<Car>>> {
            return  carDao.getAllCars().collect {
                if (it.isNotEmpty()) {
                   Result.Success(flowOf(it)) 
                } else {
                   Result.Failure(Throwable())) 
                }
             }
        }
于 2020-02-28T03:48:56.950 回答
1

这就是你的函数应该是什么样子。请注意,它不需要是suspend fun.

fun getSomeData(): Flow<Result<List<Car>>> = flow {
    carDao.getAllCars().collect {
        if (it.isNotEmpty()) {
            emit(Result.Success(it))
        }
        else {
            emit(Result.Failure<List<Car>>(Throwable()))
        }
    }
}

但它所做的只不过是添加了一个映射步骤,您可以对其进行概括。

fun <T> Flow<List<T>>.toResultFlow(): Flow<Result<List<T>>> = this.map {
    if (it.isNotEmpty()) Result.Success(it)
    else Result.Failure(Throwable())
}

于 2020-02-29T16:50:46.773 回答