Ride Sun
Ride Sun

Reputation: 2323

Is there a Flutter StreamBuilder which allows me to listen to multiple streams?

Is there a StreamBuilder which allows me to listen to multiple streams? something like:

   body: MultiStreamBuilder(
        streams: [bloc.state.stream, bloc.kind.stream],
        builder: (context) {

I don't need the snapshot like in the Flutter StreamBuilder because I can just read from the bloc

Upvotes: 5

Views: 5882

Answers (1)

Ride Sun
Ride Sun

Reputation: 2323

This is updating the UI (calling build) whenever one of the streams gets updates. I don't use the snapshot.data because I am reading the data directly from the bloc and snapshot.data contains only a bool not the real data of the streams.

class _RemoteDebuggingScreenState extends State<RemoteDebuggingScreen> {
  @override
  Widget build(BuildContext context) {
    RemoteDebugBlog bloc = BlocProvider.of(context).remoteDebugBloc;

    return Scaffold(
      body: StreamBuilder(
        stream: Observable.combineLatest2(bloc.state.stream, bloc.kind.stream,
            (b1, b2) => b1 != null || b2 != null),
        builder: (context, snapshot) {
          if (!snapshot.hasData) return Container();

          return Column(...

for more info with some nice graphics about combineLatest check this out: https://www.burkharts.net/apps/blog/rxdart-magical-transformations-of-streams/

Now knowing the above I moved this into a Widget:

import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

class DoubleStreamBuilder extends StatelessWidget {
  @override
  DoubleStreamBuilder(
      {@required this.stream1, @required this.stream2, @required this.builder});

  final Stream stream1;
  final Stream stream2;
  final Widget Function(BuildContext) builder;

  Widget build(BuildContext context) => StreamBuilder(
      stream: Rx.combineLatest2(
          stream1, stream2, (b1, b2) => b1 != null || b2 != null),
      builder: (context, snapshot) => builder(context));
}


The usage is now clear and simple like this:

 return DoubleStreamBuilder(
    stream1: settingsBloc.uiVin.stream,
    stream2: settingsBloc.isPseudoVin.stream,
    builder: (context) {
   => this updates when stream 1 or 2 have new values
   }

Upvotes: 8

Related Questions