I have 3rd party a library, where you can subscribe to some topic to receive updates on that topic (with callback). But the problem is, that when you call the subscribe method with the same topic again, the previous subscription is silently replaced with the new one.
Now, I'd like to replace the callback with Flow. So I wrote the following code:
val flow: Flow<Message> = callbackFlow {
lib.subscribe(topic) { message -> offer(message) }
awaitClose { lib.unsubscribe(topic) }
}
But when I call collect multiple times, only the last one is getting the messages.
So how can I achieve this:
- Have multiple subscriptions to the same topic
- When the last subscriber closes/cancels, unsubscribe from the given topic.
I've already looked at BroadcastChannel, but I couldn't find anything to solve the second requirement. And I've just started exploring Flows, so maybe there is some simple wrapper which I simply missed.