s0nerik / context_plus

Convenient BuildContext-based value propagation and observing. Seamlessly integrates with Flutter's built-in observability primitives.
MIT License
32 stars 4 forks source link

add Iterable<Listenable> .watch extension #15

Closed lukepighetti closed 6 days ago

lukepighetti commented 1 month ago
Screenshot 2024-08-09 at 3 43 21 PM
extension on Iterable<Listenable> {
  void watch(BuildContext context) => Listenable.merge(this).watch(context);
}
s0nerik commented 1 month ago

I like the general idea you're proposing and I see how it can potentially improve code readability by removing the repetitive .watch() calls.

The proposed implementation, though, not as much.

Using Listenable.merge() there will result in a new subscription creation on each build and disposal before the next one. That's because an instance of the listenable changes each build.

Another problem with the proposed implementation is that it's impossible to retrieve the current state of such mass-watched listenables from the method result.

I believe it would be better to have such API defined on a record instead so that the specific types of each listenable in the list are known and can be used for determining the value to be returned. Something similar to how (future1, future2).wait is defined.

I'll look into adding this after I'm done with introducing side effects into context_plus.

Thanks for a good idea!

s0nerik commented 6 days ago

The day has come! Mass-watching is now available in context_watch 5.1.0 and context_plus 4.1.0!

You can combine up to 4 observables (or observable Refs) into a record and call .watch(), .watchOnly() or .watchEffect() on them.