I need a `PublishSubject` alternative as flow. The...
# coroutines
p
I need a
PublishSubject
alternative as flow. The closest representation I found is a
Channel(RENDEZVOUS)
. However the
consumeAsFlow
function states:
If the flow consumer fails with an exception, channel is cancelled.
I don't want that. Is there an alternative for that?
l
Catch the exception?
p
That creates an implicit contract on the flow consumer, it only want to expose the flow without the consumers having the possibility to cancel the underlying implementation
l
The solution might be to use a
BroadcastChannel
(or the
broadcast
operator I think). Beware of not leaking hot resources!
l
@Paul Woitaschek can you elaborate on what you mean by "that creates an implicit contract on the flow" and why you want to void that?
p
Lets say I have a view model where I want to propagate one time events without a buffer (so that if no one is observing the flow, the values don’t get delivered later):
Copy code
class ViewModel {
  private val _events = Channel<Event>(RENDEZVOUS)
  val events : Flow<Event> get() = _events.consumeAsFlow()
}
Now I don’t want the
_events
channel to close permanently because a consumer threw an exception in it’s collect function. So now there is this implicit contract: Don’t throw an exception or the channel is broken and there will be no more events
l
makes sense thank you
@Paul Woitaschek think of this... If I were you I would you just create wrapper around the consumer that catches exceptions. Instead of doing collect(), you do collectWithExceptionhandler( consumercode: () -> Unit, errorHandler)
then you know collect will enver throw exception
p
Hm that feels like a hack. @elizarov Is there a better solution?
e
p
Absolutely. Does the last implementation miss something?