I need to share a pool of `N` subscriptions betwee...
# coroutines
t
I need to share a pool of
N
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).
Copy code
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
?