【问题标题】:Kotlin Flow - is there anything similar to LiveData's emitSource?Kotlin Flow - 有什么类似于 LiveData 的 emitSource 的吗?
【发布时间】:2021-06-17 23:20:08
【问题描述】:

我有一个函数,它接受一个返回流的参数函数,

fun <T> resultFlow(
  query: () -> Flow<T>,
  ... other parameters
): Flow<T> {
  return flow {

    val source = query()

    //!!!!    emit(source)   // I want something like emitSource like livedata has

   ...
   }

有什么办法可以让流量像这样发送吗?

【问题讨论】:

    标签: android kotlin android-livedata kotlin-flow


    【解决方案1】:

    如果您想从 Flow 中发出所有项目,这正是 emitAll() 所做的:

    fun <T> resultFlow(
      query: () -> Flow<T>,
      ... other parameters
    ): Flow<T> {
      return flow {
    
        val source = query()
    
        // Note that this will suspend until all values from the flow are collected.
        emitAll(source)
    }
    

    【讨论】:

    • 如果我不想让 emitAll 挂起与 emitSource() 一样怎么办?
    猜你喜欢
    • 2020-03-12
    • 2020-03-05
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多