基于对挂起函数的调用构建流程结果

Build Flow result based on call to a suspend function

我正在学习协程,需要一些帮助来理解基本用例。

实施非阻塞方法:

方法

因为它必须 return 一个 Flow 我不会使用 suspend(就像 return 单个项目时那样)。返回 Flowsuspend(哪种 return 是 Mono)通常是互斥的,对吗?

所以我想到了这个签名:

override fun getHistory(beforeUtcMillisExclusive: Long): Flow<Item>

正在尝试实施:

val itemInNextPeriod = itemRepository.findOneByTimestampLessThan(beforeUtcMillisExclusive)
if (itemInNextPeriod == null) {
  return emptyFlow()
} else {
  val range = calcRange(itemInNextPeriod.timestamp)
  return itemRepository.findByTimestampGreaterThanEqualAndTimestampLessThan(range.start, range.end)
}

这给了我第一行:

Suspend function 'findOneByTimestampLessThan' should be called only from a coroutine or another suspend function

我理解我们不允许在此处调用挂起函数的问题,并且 IntelliJ 提出的“添加挂起”解决方案在已经 return 流时没有意义。

所以,从 this question 我想到了使用 return flow {...}:

return flow {
  val itemInNextPeriod = itemRepository.findOneByTimestampLessThan(beforeUtcMillisExclusive)
  if (itemInNextPeriod == null) {
    return@flow
  } else {
    val range = calcRange(itemInNextPeriod.timestamp)
    return@flow itemRepository.findByTimestampGreaterThanEqualAndTimestampLessThan(range.start, 
  range.end)
  }
}

第二个存储库调用 findByTimestampGreaterThanEqualAndTimestampLessThan returns Flow<Item> 我不明白为什么我不能 return 它。

This function must return a value of type Unit Type mismatch. Required: Unit Found: Flow

return@flow returns 来自 lambda,而不是来自封闭函数。 您需要重新发送 Flow 中由 findByTimestampGreaterThanEqualAndTimestampLessThan 调用返回的 Flow 中的项目,您正在使用 flow 函数构建:

return flow {
    val itemInNextPeriod = itemRepository.findOneByTimestampLessThan(beforeUtcMillisExclusive)
    if (itemInNextPeriod != null) {
        val range = calcRange(itemInNextPeriod.timestamp)
        emitAll(itemRepository.findByTimestampGreaterThanEqualAndTimestampLessThan(range.start, range.end))
    }
}