本页尚未翻译,因此以英文显示。 参与翻译

shareReplay, ReplayValue & CompletionValue

Multicast that remembers: a bounded replay buffer, a last-value-on-close, and the chain operator that wraps a source in both.

class ReplayValue<T> { ReplayValue({int? size = 1, Duration? maxAge}); void add(T value); FxEvents<T> get live; // buffer, then live updates Future<void> close(); } class CompletionValue<T> { CompletionValue(); void add(T value); // remembered, emitted on close FxEvents<T> get live; Future<void> close(); } ConnectableEvents<T> FxEvents<T>.connectable() FxEvents<T> ConnectableEvents<T>.refCount() FxEvents<T> FxEvents<T>.shareReplay({int? size, Duration? maxAge, bool resetOnCancel = true})

Lecture

share broadcasts one run to many listeners and then forgets. A listener that arrives after an event has passed has missed it. ReplayValue is the subject that remembers: add appends to a buffer trimmed by size (default 1; null is unbounded) and maxAge, and every late subscriber replays the retained buffer first, then rides the live updates. Errors are not retained. After close, a late listener still gets the buffer, then done. fxdart events layer, after Rx's ReplaySubject.

CompletionValue is the other memory: add only remembers, and the last value is emitted on close — nothing while open, then that value and done. A late listener after close gets the same. An addError completes immediately with the error, not a remembered value. Rx's AsyncSubject. LiveValue, next, is the current-value subject with a synchronous .value read — ReplayValue of size 1 without the getter.

connectable() is the manual form: it returns a ConnectableEvents whose events feed does not subscribe the source until connect(). Listeners attached beforehand wait; late listeners miss already emitted values. refCount() connects on the first listener and disconnects on the last, reconnecting when the source allows a second listen. shareReplay is the usual spelling: multicast through a ReplayValue, connect on the first listener, late listeners see history. resetOnCancel (default true) starts a fresh buffer when the last listener leaves; false leaves the source connected forever.

fxdart events layer, after Rx's ReplaySubject, AsyncSubject, ConnectableObservable, and shareReplay.

Demo 1 · A late subscriber sees the buffer

Demo 2 · CompletionValue emits on close

Try it yourself

Exercise: shareReplay on a fromIterable, two listeners.

Related: share — multicast with no memory; late listeners miss what already passed · LiveValue — the current-value subject, with a synchronous .value · fxEvents.live on these subjects is that chain