https://kotlinlang.org logo
#coroutines
Title
# coroutines
p

Paul Woitaschek

10/08/2019, 8:15 AM
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

louiscad

10/08/2019, 9:37 AM
Catch the exception?
p

Paul Woitaschek

10/08/2019, 9:38 AM
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

louiscad

10/08/2019, 9:47 AM
The solution might be to use a
BroadcastChannel
(or the
broadcast
operator I think). Beware of not leaking hot resources!
l

Luis Munoz

10/08/2019, 3:53 PM
@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

Paul Woitaschek

10/08/2019, 4:16 PM
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

Luis Munoz

10/08/2019, 4:46 PM
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

Paul Woitaschek

10/08/2019, 9:03 PM
Hm that feels like a hack. @elizarov Is there a better solution?
e

elizarov

10/08/2019, 9:25 PM
p

Paul Woitaschek

10/09/2019, 4:55 AM
Absolutely. Does the last implementation miss something?
4 Views