FxSubscriptions
A bag of subscriptions, cancelled together — so teardown is one call instead of one field per stream.
Lecture
An object that listens to several streams has to keep every
subscription alive for one reason only: to cancel it again later. The
result is the familiar pile of nullable fields, each declared at the
top, each assigned in initState, each cancelled in
dispose — and the leak is always the one somebody forgot
to add to the third list.
FxSubscriptions collapses that to one object.
add puts a subscription in the bag and
returns it, so it reads as an expression rather than
a statement, and cancelAll() ends every one of them.
Teardown becomes a single line: Future<void> dispose() =>
subs.cancelAll();
pauseAll() and resumeAll() are the softer
version, for when the work should stop without the wiring coming
apart — a screen going to the background, a tab losing focus. A paused
subscription to a single-subscription stream buffers its events, so
nothing is lost across the gap; a broadcast stream does not
buffer for a paused listener, so events fired during the pause are
dropped.
The bag is emptied before its cancellations are awaited, so a
second cancelAll() during the wait cannot cancel anything
twice, and the same object can hold a fresh generation of
subscriptions afterwards. This is part of fxdart's events layer, modeled on
Rx's CompositeSubscription.
It pairs naturally with
stopOn: use
stopOn when a chain should end because something
happened, and FxSubscriptions when a set of
chains should end because the thing that owned them is
going away.
Demo 1 · The dispose one-liner
Demo 2 · Pausing without tearing down
Try it yourself
Exercise: addAll, and reusing the bag after a cancel.