How can a SharedFlow drop its emission when the do...
# coroutines
l
How can a SharedFlow drop its emission when the downstream is busy?
Copy code
suspend fun main(): Unit = coroutineScope {

    val sharedFlow = MutableSharedFlow<Int>()

    launch {
        sharedFlow
            .collect {
            println("Process $it")
            delay(1000)
            println("$it processed")
        }
    }

    launch {
        // 1 should be processed
        sharedFlow.emit(1)
        println("sharedFlow emits 1")

        // 2 should not be processed since downstream is busy
        sharedFlow.emit(2)
        println("sharedFlow emits 2")

        // 3 should be processed again
        delay(2000)
        sharedFlow.emit(3)
        println("sharedFlow emits 3")
    }
}
I tried BufferOverflow.DROP_LATEST, but there we need to have a buffer value > 0
Okay, I think the solution is to use a channel instead of a SharedFlow …
c
I don’t understand the question. What is the problem you’re trying to solve? If you want shared flow to have a buffer, pass
extraBufferCapacity
to its constructor.
c
Yeah, this is something that confused me for a while, but
DROP_LATEST
only works when there is some “buffer” (either
replay
or
extraBufferCapacity
), and the behavior is the same with both Channels and SharedFlows. I’m not really sure why this is the case, but I guess it needs that internal buffer to know when its full or busy?
f
What would you drop if there is no buffer?
j
Technically there is no guarantee that the first launch has actually reached the
collect
call by the time you emit the first element to the shared flow