can anybody using coroutine 1.4.0-M1 confirm that ...
# coroutines
n
can anybody using coroutine 1.4.0-M1 confirm that a
Copy code
MutableSharedFlow(replay = 0)
doesn't emit values ? 😕 the same code works if replay = 1 (but I don't want to replay first value each time 😢 )
m
Works for me. Prints “hello”.
n
ok I just find out it's because I use tryEmit 😢
ahhh I think it needs a buffer
ok that's it, just needs a buffer value, good to know
m
Hmm. I don’t think it should require a buffer
n
here's my sample
Copy code
fun main() {
    val mSharedFlow = MutableSharedFlow<Int>(extraBufferCapacity = 10)
    val sharedFlow: SharedFlow<Int> = mSharedFlow.asSharedFlow()


    val scope = CoroutineScope(Dispatchers.Default)
    val job = scope.launch {
        sharedFlow.collect {
            println("got $it")
            if (it == 0) {
                cancel()
            }
        }
    }
    runBlocking {
        mSharedFlow.emit(1)
        mSharedFlow.emit(2)
        mSharedFlow.emit(0)
    }
}
if you use tryEmit, with a buffer of 0:
nothing is printed 😄
with a buffer of one : got 1
it works if you use delay between the tryEmit
m
Yeah according to the code it requires either buffer size > 0 or replay size > 0. The latter is confusing
n
of course if I change the bufferOverflow policy to drop it works (with either the latest or oldest, it actually logic now I get the buffer part
m
I think it cannot know whether it would suspend in that case so it just assumes that it can’t.
n
Copy code
val mSharedFlow = MutableSharedFlow<Int>(extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_LATEST)
m
There are many options. What do you want to achieve?
n
I was just playing with it, I just wanted a simple equivalent of a PublishSubject (if you know Rx)
m
Isn’t that like
StateFlow
and replays?
n
a PublishSubject has no replay, and stateflow unfortunatelly reemit the first value, but sharedflow works exactly like I want now
m
So you have no initial value either?
n
yes it is used to transmit events usually (edited)  things you want to handle only once like errors
m
So
SharedFlow
with no replay makes most sense. What should happen on backpressure?
n
I usually don't need backpressure but here we can often drop oldest
depends on the case, right no wi was just trying to display the latest error, but I can just use emit which will work too
m
tryEmit
with a
DROP_LATEST
buffer should be fine.
A shared flow configured with a BufferOverflow strategy other than SUSPEND (either DROP_OLDEST or DROP_LATEST) never suspends on emit, and thus tryEmit to such a shared flow always returns true.
n
yes it should work I'm pretty happy about this new coroutine addition anyway !
➕ 2