このページはまだ翻訳されていないため、英語で表示されます。 翻訳に参加する

FxSubscriptions

A bag of subscriptions, cancelled together — so teardown is one call instead of one field per stream.

class FxSubscriptions { int get length; bool get isEmpty; bool get isNotEmpty; StreamSubscription<T> add<T>(StreamSubscription<T> subscription); void addAll(Iterable<StreamSubscription<void>> subscriptions); Future<void> cancelAll(); // cancel every one, and empty the bag void pauseAll(); void resumeAll(); }

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. Paused subscriptions buffer rather than drop, so nothing is lost across the gap.

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. fxdart events layer, after 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.

Related: stopOn — teardown driven by an event rather than by an owner's lifecycle · fxEvents — the chain whose listen hands you the subscriptions this holds · LiveValue — has its own close(), and is not held by this bag