https://kotlinlang.org logo
Title
i

Ivan Đorđević

10/26/2021, 9:19 AM
Hi, is there a version of
SharedFlow
that caches values (like
replayCache
) but DOESN'T play them back automatically to new subscribers?
w

wbertan

10/26/2021, 9:25 AM
🤔 We use this:
fun <T> MutableSingleSharedFlow() = MutableSharedFlow<T>(
    replay = 1,
    extraBufferCapacity = 1,
    onBufferOverflow = BufferOverflow.DROP_OLDEST
)
Not sure it “DOESN’T play them back automatically” 🤔
i

Ivan Đorđević

10/26/2021, 9:26 AM
Thanks! Although it seems like it would, because
replay = 1
so it seems it would replay one value
b

bezrukov

10/26/2021, 9:26 AM
use replay = 0, and extraBufferCapacity=desired buffer size to achieve this
i

Ivan Đorđević

10/26/2021, 9:27 AM
@bezrukov I tried that, but then I can't access the cache since
replayCache.size() == 0
still even after emitting something
b

bezrukov

10/26/2021, 9:32 AM
ah I see, you still need to have a direct access to the buffer. So I don't think there is a good built-in way to achieve this. You probably can play with
flow.drop(flow.replayCache.size())
but I don't think it's robust because of different locks (I mean let's say replayCache contains [A,B,C] when you called it, but when you subscribed to it, A is dropped, and replay cache is [B, C, D], so you won't receive D).
d

Dominaezzz

10/26/2021, 9:40 AM
You could subscribe to the
SharedFlow
early and maintain a list of n items emitted. Maybe even share the shared flow subscription, then you can use the new replay cache. (Although I don't think I'd call this a cache).