#37 - Flutter Stream with StreamBuilder

Date: 2018-12-01 12:00 - dart

Flutter Stream that builds a useful StreamBuilder with RxDart.

class BuildStream<T> extends Stream<T> {
  final BehaviorSubject<T> _subject;

  BuildStream(BehaviorSubject<T> subject) : _subject = subject;

  Widget widget({
    @required Widget build(BuildContext context, T data),
    Widget error(BuildContext context, Object error),
    Widget loading(BuildContext context),
  }) {
    assert(build != null);
    return StreamBuilder<T>(
      initialData: _subject.value,
      stream: _subject.stream,
      builder: (BuildContext context, AsyncSnapshot<T> snapshot) {
        if (snapshot.hasError)
          return error != null ? error(context, snapshot.error) : Container();
        else if (!snapshot.hasData)
          return loading != null ? loading(context) : Container();
        return build(context, snapshot.data);
      },
    );
  }

  @override
  StreamSubscription<T> listen(
    void Function(T event) onData, {
    Function onError,
    void Function() onDone,
    bool cancelOnError,
  }) =>
      _subject.stream.listen(
        onData,
        onError: onError,
        onDone: onDone,
        cancelOnError: cancelOnError,
      );
}

// example
class BLoC {
  BehaviorSubject<int> _counter = BehaviorSubject<int>(seedValue: 0);
  BuildStream<int> get counter => BuildStream(_counter);

  void incrementCounter() {
    _counter.value += 1;
  }

  void dispose() {
    _counter.close();
  }
}

Previous snippet | Next snippet