Emit Flow via another suspend function in Kotlin - TagMerge
2Emit Flow via another suspend function in KotlinEmit Flow via another suspend function in Kotlin

Emit Flow via another suspend function in Kotlin

Asked 1 years ago
2
2 answers

You can try to use emitAll function for your case:

fun myFunction1(): Flow<String> = flow {
    /*some code*/
    emitAll(myFunction2())
}

fun myFunction2(): Flow<String> = flow {
    /*some code*/
    emit("hello")
}

emitAll function collects all the values from the Flow, created by myFunction2() function and emits them to the collector.

And there is no reason to set a suspend modifier before each function, flow builder isn't suspend.

Source: link

1

Unless you have a very specific reason the functions returning a Flow from your repo shouldn't be suspending (As the flow{} builder isn't suspending). Since the suspending operation is collecting (waiting for values to come out of it).

From the code you've provided you're looking for the flatMapLatest function. Docs here

class Repo {

  fun function1() = 
    flow {
      val value = doSomething()
      emit(value)
    }
    .flatMapLatest { emittedValue -> function2() }
  fun function2() = flow {...}
}

Source: link

Recent Questions on kotlin

    Programming Languages