tseisel
10/27/2020, 10:10 AMN
subscriptions between multiple one time subscribers. My current implementation uses BroadcastChannel
s to keep active subscriptions to source `Flow`s. Whenever a new subscriber requests, the eldest subscription is terminated by cancelling the BroadcastChannel
(LRU caching).
suspend fun getLastFoo(id: String): Foo {
val broadcast: BroadcastChannel<Foo> = getCachedSusbcription(id) ?: initiateSubscription(id)
return broadcast.consume { receive() }
}
fun initiateSubscription(id: String): BroadcastChannel<Foo> {
val broadcast = getExpensiveFooFlow(id).broadcastIn(scope)
putInCacheAndEvictEldest(id, broadcast)
return broadcast
}
fun getExpensiveFooFlow(id: String): Flow<Foo> { ... }
I'd like to migrate my code to use Flow.stateIn
, but StateFlow
does not have a cancel
function to unsubscribe the source flow. How to implement this use-case with StateFlow
?