Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is ChangeNotifier prefered over an Observable in Flutter?

I've been struggling to understand when ChangeNotifier is preferred over Rxdart's Observable, or streams in general.

According to Flutter's docs:

A class that can be extended or mixed in that provides a change notification API using VoidCallback for notifications.

ChangeNotifier is optimized for small numbers (one or two) of listeners. It is O(N) for adding and removing listeners and O(N²) for dispatching notifications (where N is the number of listeners).

Still, I'm not sure what ChangeNotifier can offer that an Observable or Stream cannot.

like image 834
Eliya Cohen Avatar asked Nov 06 '19 09:11

Eliya Cohen


1 Answers

Some updates since you asked this question

  • Observable is deprecated and you can just use extension functions on Stream
  • ChangeNotifier performance: O(1) for adding listeners and O(N) for removing listeners and dispatching notifications

But I would focus less on performance and more on the use-case. ValueNotifier is a lighter-weight solution, but not as robust as Streams.

This Reddit thread does a great job describing the difference in use-case. As does this StackOverflow post.

But to summarize:

  • Streams are great when working in your model/networking layer (or business logic). "Streams represent a series of events or pieces of information (from zero to infinite) that are produced from a source. This naturally makes sense for network packets, video frames, analytics events, error reporting, etc."
  • ValueNotifier is great for relaying state changes back to your UI. "If you have an object with members that might change, and you want to know when some or all of them change, then all you need to do is mixin ChangeNotifier within that class, and then invoke notifyListeners whenever something changes."
like image 130
Kyle Venn Avatar answered Nov 05 '22 20:11

Kyle Venn