androidkotlinkotlin-coroutineskotlin-flowandroid-ktx

How add dynamic values in Kotlin Flow


if we know list values to be processed in Kotlin flow then we can follow the below function

  flow {
          (1..1000).forEach {
            delay(1000) //Process Data
            emit(it.toLong())
          }
       }.collect{
            delay(2000)
            print(it)
        }

where we know we are going to print values from 1 to 1000

In my case, I do not have input value at the beginning of the flow. I want to start the flow when I have value 1 and start the process of the data meanwhile if I have a new value then I have to add it in Queue wait till value 1 gets processed then start the process of the new value.

Basically, I want to add value outside of the flow block, Is any solution available to achieve that?


Solution

  • You can use a SharedFlow for that with a buffer. It would be something like this:

    val myFlow = MutableSharedFlow<Long>()
    

    You can emit values like this:

    (1..1000).forEach {
        delay(1000) //Process Data
        println("Emitting $it")
        myFlow.emit(it.toLong())
    }
    

    And collect them like this:

    myFlow
        .buffer()
        .collect {
            delay(2000)
            println("Received: $it")
        }
    

    If you don't use the buffer operator, every time you emit a value, the emision gets suspended until collect finishes its work.