Search code examples
dartflutterrxdart

How to conditionally add an error to an Observable in RxDart?


Using a Dart StreamTransformer, I can evaluate a stream value and choose to emit it based on some condition (e.g. sink.add(value)), or add an error (e.g. sink.addError('Enter a valid number')).

How would I do best do this using RxDart's fluent operators? I could use .map to evaluate the value and use addError('message') against the subject. However, is there some better way?


Solution

  • Stream.map will forward thrown exceptions on as error events in the stream.

    var result = values.map(
      (value) => someCondition(value) ? value : throw 'Enter a valid number ');