Flutter: Using a global stream?

Viewed 2258

Let's imagine you define a stream here:

Stream<MyUser> user = getStream();

void main() => runApp(MyApp());

Now it can be used to trigger StatefulWidget changes or with StreamBuilder anywhere in the widget tree.

class UserProfileState extends State<UserProfile> {
  MyUser _user;

  @override 
  initState() {
    super.initState();
    user.listen((user) => setState(() => _user = user ))
  }
}

Are there any technical problems with a global stream/observable like this in Flutter? I've not been able to find examples of this pattern outside of inherited widgets or redux (which are far more complex).

1 Answers

There is nothing agains global streams.
It's usually a good idea to not access global streams directly, but instead provide them as a service (for example using InheritedWidget in Flutter), so that dependencies are easier to handle and they are is easy to mock for tests.

Redux is perhaps far more complex than a single stream when you have a single stream. When the app grows it is likely to reduce complexity though compared to using streams directly.

The main problem with streams will probably emerge if you have multiple listeners for a single stream.

  • A single-subscription stream (default) throws an exception when an additional consumer tries to listen.

  • A broadcast stream drops events when no consumer is listening.

See https://www.dartlang.org/articles/libraries/broadcast-streams for more details.

Related