The bloc ecosystem vs Juice

1. Family snapshot

Versions read (felangel/bloc master pubspecs, 2026-09-16): bloc 9.2.1, flutter_bloc 9.1.1, bloc_concurrency 0.3.0, hydrated_bloc 11.0.0, replay_bloc 0.3.0, bloc_test 10.0.0, bloc_lint 0.4.2, bloc_tools 0.1.0-dev.24. Sources read: raw.githubusercontent.com/felangel/bloc/master/packages/<pkg>/lib/src/ — bloc.dart, emitter.dart, bloc_base.dart, bloc_observer.dart, the three bloc_concurrency transformers, hydrated_bloc.dart, hydrated_storage.dart, replay_bloc.dart, change_stack.dart, bloc_test.dart, mock_bloc.dart, when_listen.dart, bloc_builder/listener/selector/provider.dart, bloc_lint linter.dart + rules/. Docs: https://bloclibrary.dev/bloc-concepts/, /flutter-bloc-concepts/, /architecture/, /lint/, /lint-rules/*; pub.dev pages for each package and for bloc_devtools_extension; https://github.com/felangel/bloc/issues/2748.

Philosophy. Bloc is a small, stream-shaped core: BlocBase holds state behind a broadcast StreamController; Bloc pipes add(event) through a per-handler EventTransformer into on<E> handlers that receive an Emitter; one global Bloc.observer sees create/event/change/transition/error/done/close. Felix’s reason to prefer Bloc over Cubit is traceability: “One of the biggest advantages of using Bloc is knowing the sequence of state changes as well as exactly what triggered those changes.” Everything else (hydrated, replay, concurrency, test, lint) is a mixin, a transformer or a tool on those three seams (emit, observer, transformer). Layering: data → repository → bloc → presentation; “sibling dependencies between two entities in the same architectural layer should be avoided at all costs” — bloc-to-bloc goes through BlocListener in the UI or a shared reactive repository.

2. Mechanism catalog

Event handlers + event transformers (on<E>, Bloc.transformer)

  • What it does: one handler per event type; a transformer decides how same-handler events interleave; Bloc.transformer sets the global default.
  • How it works: add() asserts a handler exists (debug), calls onEvent, adds to a broadcast _eventController. on<E> subscribes (transformer ?? Bloc.transformer)(events.where((e) => e is E).cast<E>(), mapper). The mapper builds a fresh _Emitter(onEmit) per event plus a sync broadcast controller whose onCancel: emitter.cancel, runs handler(event, emitter) with finally { emitter.complete(); controller.close() }, and returns controller.stream — a handler’s lifetime is modelled as a stream that transformers flatten, queue, drop or switch. Default is events.map(mapper).transform(_FlatMapStreamTransformer()) = concurrent. Matching is e is E, so a handler on a base event type receives the whole hierarchy and its transformer serializes across subtypes.
  • Juice today: has-under-another-name (UseCaseBuilder.concurrency, core/event_dispatcher.dart). partial: Juice matches by exact runtimeType, so there is no cross-type lane — ROADMAP records juice_sync’s Retry↔Discard “documented, deferred cross-type window” for this reason.
  • Gap value: Med — any bloc with several mutation events on one collection needs one FIFO across types.
  • Adoption sketch: a lane on UseCaseBuilder (concurrency: sequential, lane: 'queue'): the dispatcher keys _tails/_running by lane when given. Core, cost S. Not base-type handlers.
  • Doctrine fit: needs a knob (lane), but it widens the key of the existing concurrency knob rather than adding a purpose; ROADMAP already names the need (“a bloc-owned FIFO closes it; no consumer yet”).

bloc_concurrency: sequential / droppable / restartable

  • What it does: the three non-default interleavings as transformers.
  • How it works: sequential = events.asyncExpand(mapper). droppable = a hand-written _ExhaustMapStreamTransformer that discards events while mappedSubscription != null and resets on onDone. restartable = events.switchMap(mapper) from stream_transform; the fence is indirect and elegant: switchMap cancels its subscription to the previous handler’s stream → the sync controller’s onCancel runs emitter.cancel() → _isCanceled = true, all forEach/onEach subscriptions in _disposables are cancelled, the completer completes, and every later emit() from the superseded handler is a no-op (if (!_isCanceled) _emit(state)). Side effects are not undone; docs warn it is “only for asynchronous APIs”.
  • Juice today: partial — concurrent/sequential/droppable shipped in 1.5.0 (_sequential chains per-type _tails, _droppable uses _running); restartable is a comment in event_concurrency.dart and ROADMAP tee-up item 3, whose epoch-fence design matches bloc’s semantics exactly.
  • Gap value: Med (typeahead, scrubbing, latest-search-wins).
  • Adoption sketch: per-type epoch in EventDispatcher; the UseCaseContext emits no-op when epoch != current, logging state_emission_skipped with reason superseded; the superseded event is CancellableEvent.cancel()led so isCancelled doubles as bloc’s emit.isDone. Core, cost S–M.
  • Doctrine fit: fits (fourth value of the one knob). Gate stands: a real consumer.

Emitter.forEach / Emitter.onEach

  • What it does: binds a stream to state for the life of one handler, cancellation tied to handler and bloc.
  • How it works: onEach subscribes, pushes subscription.cancel into _disposables, and returns Future.any([emitter.future, completer.future]).whenComplete(cancel) — the binding ends when the stream completes or the emitter is cancelled (restartable/close). forEach is onEach with onData: (d) => call(onData(d)). complete() asserts _disposables.isEmpty (“An event handler completed but left pending subscriptions behind… unawaited emit.forEach”); call() asserts !_isCompleted (“emit was called after an event handler completed normally… unawaited future”). close() cancels every live emitter and awaits their futures before closing state.
  • Juice today: lacks. Every streaming package hand-rolls it on the bloc: juice_location/lib/src/location_bloc.dart:82, juice_llm/lib/src/llm_bloc.dart:290, juice_realtime/lib/src/realtime_bloc.dart:154, juice_connectivity:72, juice_lifecycle:55 (_sub = x.listen(...), cancel in close()); StatefulUseCaseBuilder is the only helper.
  • Gap value: High for package authors (five packages repeat the pattern; the leak surface is per-package), Med for apps.
  • Adoption sketch: BlocUseCase.bindStream<T>(stream, {required BlocState Function(T) onData, groupsToRebuild, onError}), returning a future that completes on stream done, CancellableEvent cancel, or bloc close (the dispatcher’s close() cancels registered bindings); emits go through emitUpdate so groups and telemetry apply; the executor asserts no binding outlives execute() unless the builder is StatefulUseCaseBuilder (long-lived subscriptions are its stated purpose). Core, cost M. Migrate juice_location first.
  • Doctrine fit: fits (helper, no knob; makes gotcha 8 partly automatic).

Bloc-wide == dedup and emit-after-close

  • How it works: BlocBase.emit throws StateError('Cannot emit new states after calling close'); if (state == _state && _emitted) return; is always-on (first emit always passes); onChange runs before the store.
  • Juice today: has-under-another-name — StatusEmitter._emit throws on closed; dedup is per-call skipIfSame, deliberately not bloc-wide (AGENTS §4c: a blanket mode “would swallow intentional re-emits”). Not a gap. Gap value Low.

BlocObserver (+ MultiBlocObserver, Transition/Change)

  • What it does: one global object receives onCreate, onEvent, onChange(Change{currentState,nextState}), onTransition(Transition{currentState,event,nextState}), onError, onDone(event[,error]) (9.1.0), onClose; 9.2.0 adds MultiBlocObserver fan-out.
  • How it works: BlocBase captures Bloc.observer at construction (final _blocObserver = Bloc.observer), so an observer installed later misses existing blocs; hooks are @protected @mustCallSuper instance methods delegating to it. onTransition fires only from on<E>’s onEmit; no ids, no timing — onDone cannot be paired with its transitions when same-type events overlap.
  • Juice today: has-under-another-name — the JuiceLogger seam + typed context['type'] taxonomy and DevtoolsJuiceLogger as the tee; StreamStatus(state, oldState, event) is a Transition with status attached. partial: no typed onCreate; consumers parse string-typed maps (the DevTools extension re-derives a model in telemetry_model.dart).
  • Gap value: Low–Med (tooling authors).
  • Adoption sketch: promote the extension’s model into juice_observability as sealed class JuiceTelemetry + JuiceTelemetry.parse(context) — typed consumption on the existing seam. Cost S.
  • Doctrine fit: fits only as a decoder on the logger seam; a separate observer object would be a second knob for the same purpose — reject that form.

Cubit

  • How it works: abstract class Cubit<State> extends BlocBase<State> — three lines; methods call emit. The observer sees Changes with no event; prefer_cubit/prefer_bloc/prefer_void_public_cubit_methods police the style.
  • Juice today: has-under-another-name for the ceremony problem only (InlineUseCaseBuilder keeps the event, gives ctx.emit.update(...)).
  • Gap value: Low. Doctrine fit: conflicts (one use case per event; Felix’s traceability argument is Juice’s argument). Reject.

hydrated_bloc

  • What it does: persist every state change; restore at construction.
  • How it works: HydratedMixin.hydrate() runs in the constructor; __storage.read(storageToken) is synchronous (the Hive CE box is already in memory), _state = fromJson(json) ?? super.state, and the state getter is overridden to _state ?? super.state. onChange writes toJson(nextState) after every emit. _traverseWrite validates the tree: atomics pass (non-finite num → NIL), List/Map recurse with a _seen stack for cycle detection (HydratedCyclicError), custom objects get .toJson() called dynamically, anything else throws HydratedUnsupportedError — a non-serializable field fails at first write, not at restore. Key = storagePrefix (runtimeType; override for minification) + id (multi-instance). Storage (read sync, write/delete/clear/close async) is HydratedStorage over one Hive CE box hydrated_box behind a synchronized Lock, HydratedStorageDirectory.web sentinel, optional AES cipher, one-shot migration of the legacy .hydrated_bloc.json. 10.1.0 added onHydrationError → HydrationErrorBehavior.overwrite|retain (default overwrite: a corrupt read is clobbered by the next write). No schema versioning or migration — apps branch inside fromJson.
  • Juice today: partial. The substrate exists (juice_storage 2.2.0, awaitable initialize()), persistence is per-package behind seams (ThemePersistence.load/save, notes_app auto_save_use_case), but there is no generic “restore this bloc’s state, save on emit” capability and no BlocState in the family has toJson (grep *_state.dart: 0).
  • Gap value: High for app authors (settings, drafts, offline-first) — the most-used bloc add-on; every Juice app re-derives it.
  • Adoption sketch: a StatePersistence<TState> seam in core (Future<Persisted<TState>?> load(), Future<void> save(TState, {required int version})), optional on the JuiceBloc constructor; a built-in HydrateEvent (droppable, via initialEventBuilder) that emitWaitings then emitUpdates the restored state on a hydrate group — the awaitable storage becomes an honest WaitingStatus instead of bloc’s sync trick; saves queue on a built-in sequential PersistStateEvent triggered from StatusEmitter.emitUpdate only. juice_storage ships StorageStatePersistence (Hive) + InMemoryStatePersistence (fake). Fail loud where bloc is silent: version + required migrate(from, json); unknown version → emitFailure, never overwrite. Cost M.
  • Doctrine fit: fits (seam + default + fake; events → use cases; groups). Flagged for veto: when no seam is passed the built-in events are simply not registered — absence of a feature, not a fallback.

replay_bloc

  • What it does: undo/redo with bounded history and a replay filter.
  • How it works: ReplayBlocMixin overrides emit: before super.emit(state) it pushes _Change(old, new, redo, undo) onto _ChangeStack — two ListQueues (_history, _redos); add clears redos and trims to limit. undo() moves the last change to redos and runs its closure, which synthesizes a private _Undo event, calls onEvent + onTransition (the observer sees undo as a real transition) and super.emit(old); redo mirrors. shouldReplay(state) is consulted at replay time; non-replayable entries are skipped recursively (canUndo = _history.any(shouldReplay)). ReplayEvent is the required event base so _Undo/_Redo type-check.
  • Juice today: lacks (grep undo|redo in packages/juice/lib: 0).
  • Gap value: Med — editors (notes_app editor bloc is the in-repo candidate).
  • Adoption sketch: mirror RetryableUseCaseBuilder’s emit interception: UndoableUseCaseBuilder wraps a builder, records (oldState, newState, groups) on each emitUpdate into a ChangeStack<TState> held on the bloc (behavior on the bloc, not in state — gotcha 5), and registers built-in UndoEvent/RedoEvent use cases (sequential) that re-emit with the recorded groups plus a history group for canUndo/canRedo widgets. limit and shouldReplay as constructor args. Core, cost M.
  • Doctrine fit: fits (decorator builder, events, groups, no state bloat). Gate: a real editor consumer.

bloc_test (blocTest, MockBloc, whenListen)

  • How it works: testBloc swaps Bloc.observer for a _TestBlocObserver that forwards to the previous one and collects onErrors; inside runZonedGuarded: setUp, build(), optional bloc.emit(seed()), stream.skip(skip).listen(states.add), await act?.call(bloc) (errors captured only if errors: given), await wait, await Future.delayed(Duration.zero), await bloc.close(), then expect(states, wrapMatcher(expected)); on mismatch a diff_match_patch diff is appended and, if '$states' == '$expected' with unequal objects, “Please ensure state instances extend Equatable, override == and hashCode”. MockBloc is a mocktail Mock with stream/close pre-stubbed; whenListen re-stubs bloc.state as each stubbed emission passes.
  • Juice today: has-under-another-name — src/testing/bloc_tester.dart (send + 10 ms delay, sendAndWaitForResult, expectStatusSequence, expectWasWaiting/Failure, waitForEmissions). partial: no seed, no declarative act/expect, no error matcher, no diff, no mocks — and no test in the repo uses it (grep BlocTester|.tester() over *_test.dart: 0); packages test with hand-written settle().
  • Gap value: Med (every package’s tests; consumers’ first bloc test).
  • Adoption sketch: juiceTest<TBloc,TState>(desc, build:, seed:, act:, wait:, expect: [WaitingStatus, UpdatingStatus], expectGroups:, errors:, verify:) in package:juice/testing.dart on top of BlocTester; seed via the @visibleForTesting emit; errors via a test BlocErrorHandler; mismatch prints the status/group diff. Groups make the assertion richer than bloc’s (rebuild targeting becomes testable). Cost S–M. Gate: port juice_theme’s tests.
  • Doctrine fit: fits; “demonstrate in full” says the framework’s own tests should use it.

bloc_lint (+ bloc_tools LSP)

  • How it works: a standalone linter — not custom_lint, not the analyzer element model. linter.dart scans/parses with _fe_analyzer_shared’s Parser; rules are token-level Listeners (beginMethod, beginMetadata) — avoid_public_bloc_methods fires when enclosingDeclarationName.endsWith('Bloc') and the name is not allow-listed. It runs only when pubspec.lock contains bloc and analysis_options.yaml has bloc: rules:; IDE integration is bloc_tools’ language server (lsp_server_ce). Nine rules: avoid_build_context_extensions, avoid_flutter_imports, avoid_public_bloc_methods, avoid_public_fields, prefer_bloc, prefer_build_context_extensions, prefer_cubit, prefer_file_naming_conventions, prefer_void_public_cubit_methods.
  • Juice today: has — juice_lint 0.1.0 (custom_lint, three rules on the resolved model, TypeChecker scoped to package:juice). partial on coverage: ROADMAP phase 3 named use-case-per-file, no-cross-feature-deps, relay-not-listener; none built.
  • Gap value: Med.
  • Adoption sketch: three rules, cost S each: juice_state_read_before_await (a bloc.state read stored in a local, an await, then that local passed to emit* in a non-sequential builder — AGENTS gotcha 3), juice_feature_bloc_dependency (a feature package importing another feature bloc — ROADMAP invariant 2), juice_public_state_field (bloc’s avoid_public_fields). Skip avoid_public_bloc_methods: the canonical shape has thin wrappers (void load() => send(LoadFooEvent())).
  • Doctrine fit: fits.

flutter_bloc widgets (BlocProvider, MultiBlocProvider, BlocBuilder, BlocListener, BlocSelector)

  • How it works: BlocProvider is provider’s InheritedProvider — lazy create, dispose: (_, bloc) => bloc.close() for create only (never .value), _startListening marks dependents per emission so context.watch works. MultiBlocProvider extends MultiProvider. BlocListener subscribes to bloc.stream, calls listener when listenWhen?.call(_previousState, state) ?? true, and re-subscribes when the bloc instance changes. BlocBuilder is literally a BlocListener with listenWhen: buildWhen, listener: setState; BlocSelector setStates only when selector(state) != _state.
  • Juice today: has-under-another-name: BlocScope.register/get/lease + BlocLifecycle + FeatureScope/CleanupBarrier (ownership explicit, not tree-positional); StatelessJuiceWidget(groups) via denyRebuild; JuiceBuilder(buildWhen: (status)), JuiceMultiBuilder; JuiceSelector/bloc.select (==) and selectWith. Side effects: JuiceWidgetState.prepareForUpdate(status) fires once per new status (the listener hook); StatelessJuiceWidget has only onStateChange (a filter). No BlocListener widget by doctrine; bloc-to-bloc is StateRelay/StatusRelay/EventSubscription with leases.
  • Gap value: Low. listenWhen(previous, current) is expressible because StreamStatus carries oldState. Adoption sketch: none; document prepareForUpdate as the listener hook in AGENTS.

DevTools story

  • How it works: there is no official bloc DevTools extension — issue #2748 “[Proposal] official bloc devtools” is open, “In progress”, assigned to felangel. Third-party bloc_devtools_extension 0.2.0 (unverified publisher) installs a BlocObserver, registers a service extension, and ships a devtools_extensions tab with History (time-travel slider, state replay), Graph, Performance.
  • Juice today: has — juice_observability 0.5.0 DevtoolsJuiceLogger (postEvent juice:<type>, 512-char clipping) + a packaged extension (Timeline/Spans/Blocs/Problems). Ahead of the family. Worth stealing later: state diff (oldState/state are already on the wire) and time-travel replay — which needs serializable state, i.e. depends on hydration.
  • Gap value: Low. Doctrine fit: already built.

3. Not worth adopting

  • Cubit — eventless emit conflicts with one-use-case-per-event; Felix’s own traceability argument favors Juice’s shape.
  • Bloc-wide == dedup — Juice chose per-call skipIfSame for the waiting→waiting reason; a blanket mode is a silent fallback.
  • BlocProvider tree ownership — BlocScope lifecycles + leases + LeakDetector are strictly more explicit; a provider tree would be a parallel path.
  • BlocListener widget — “relays not listeners”; prepareForUpdate and relays cover it.
  • avoid_public_bloc_methods / prefer_cubit / prefer_bloc / *_build_context_extensions — stylistic, and contradict the canonical wrapper methods and bloc getter.
  • Base-type event handlers (e is E) — would undermine exact-type matching that the dispatcher and juice_generic_event rely on; lane gets the benefit.
  • HydrationErrorBehavior.overwrite default and synchronous hydrate — clobbering an unreadable persisted state is the silent fallback CLAUDE.md forbids; the sync read relies on an already-open box. Adopt hydration with versioning + WaitingStatus instead.
  • bloc_lint’s token-level architecture — fast, but name-suffix heuristics; the resolved-type approach is the better base.

4. Top 5 recommendations (ranked)

  1. bindStream (bloc’s emit.forEach) on BlocUseCase. Five shipped packages hand-roll listen + cancel-in-close; the framework owns the cancellation contract only by convention. A helper whose future ends on stream-done, CancellableEvent.cancel, or bloc close, emitting through emitUpdate (groups + telemetry intact) and asserting no binding outlives a non-stateful builder, removes a leak class and makes restartable implementable (a superseded run’s bindings die with its epoch). Gate: migrate juice_location (location_bloc.dart:82) and juice_llm generation (llm_bloc.dart:290); the bloc-side subscription fields and close() bodies must shrink, verified under LeakDetector in their tests.

  2. State hydration via a StatePersistence<TState> seam, with versioned fail-loud migration. The most-used bloc add-on has no Juice equivalent and every app re-derives it (theme, i18n, notes autosave). Core seam + juice_storage default + in-memory fake; restore as an honest WaitingStatus; save only on emitUpdate, sequential; refuse unknown schema versions. Gate: one consumer that already persists (notes_app editor or juice_theme) migrated without a second persistence path, plus a decision on whether ThemePersistence/juice_i18n seams fold into it (one knob) or stay domain-specific.

  3. juiceTest and dogfood BlocTester. The tester exists and nothing uses it; bloc’s testing story is one declarative function with a diff. Add seed, expect: [status types], expectGroups, errors, a sequence diff; port one package. Gate: the juice_theme port reads shorter than the settle() version and asserts group targeting the current tests don’t.

  4. Three lint rules on the resolved model. juice_state_read_before_await (the #1 latent bug, today only prose in AGENTS §4), juice_feature_bloc_dependency (ROADMAP invariant 2), juice_public_state_field. Gate: planted sentinels across the five juice_examples apps fire; zero false positives on the 28 packages.

  5. restartable plus a lane key on the existing concurrency knob. Both are designed in the ROADMAP; bloc’s source confirms the semantics (fence emissions, never side effects). Keep both gated on a consumer, but note lane’s gate is nearer than it looks: juice_sync’s Retry↔Discard window is a documented defect waiting for it.

5. Things Juice does better than this family

  • send() returns the processing future; add() is fire-and-forget. sendAndWait/sendForResult have no bloc equivalent — bloc_test needs Future.delayed(Duration.zero) and a wait: knob to compensate.
  • StreamStatus ⊃ Transition. Bloc’s Transition exists only inside onTransition; Juice puts (state, oldState, event) plus Waiting/Failure(error, errorStackTrace)/Canceling on every emission the UI sees.
  • Named rebuild groups vs buildWhen. Bloc invalidates by per-widget predicates over whole states; Juice’s groups are intent-named, cross-widget, chosen at the emit site, and testable via status.event?.groupsToRebuild.
  • Explicit ownership. BlocLifecycle.permanent/feature/leased, BlocLease, FeatureScope, CleanupBarrier, LeakDetector vs BlocProvider’s tree-positional lifetime and the .value-doesn’t-close footgun.
  • Telemetry spans. executionId + elapsedMicros pair start/end under concurrent overlap; bloc’s onDone (9.1.0) has no id and no timing.
  • A shipped DevTools extension (bloc’s official one is an open issue).
  • Lint on the resolved element model; bloc_lint matches endsWith('Bloc') on unresolved tokens.
  • Cancellation and timeout as event concerns. CancellableEvent + TimeoutSupport + emitCancel/CancelingStatus; bloc’s only cancellation is restartable’s fence (emit.isDone).
  • Per-item async state (EntityStatuses + guardEntity) and retry as a builder decorator (RetryableUseCaseBuilder + BackoffStrategy); bloc has neither primitive.
  • Bloc-to-bloc is first-class (StateRelay/StatusRelay/EventSubscription with leases); bloc’s doctrine is “avoid at all costs; go through the UI or a repository”.
  • Use-case errors are structured. Bloc rethrows from an unawaited handleEvent() into the zone; Juice logs use_case_error with the execution id and routes to BlocErrorHandler, while still throwing on emit-after-close.

This site uses Just the Docs, a documentation theme for Jekyll.