reactive_data_manager 2.0.0
reactive_data_manager: ^2.0.0 copied to clipboard
Sync data across the app
Changelog #
2.0.0 - 2026-10-12 #
This release contains everything since 1.1.0 (the 1.2.0 and 1.3.0 changes were
never published separately). It is a major version because it changes
observable behaviour that 1.x callers may depend on (see "Changed (behaviour
fixes)" and the compatibility notes below): concurrent getData calls now join
instead of cancel, clearCache/evict discard in-flight results,
updateData supersede semantics changed, and invalidating a watched key
refetches it. The public API of 1.1.0 is otherwise
kept (the fetcher field remains as a deprecated getter).
Changed (behaviour fixes) #
getDatano longer cancels the in-flight fetch. Concurrent calls for one key join a single fetch and all complete with its result or error; previously every call hit the fetcher and all but the last future hung forever. OnlyforceRefresh: truestarts a new fetch, and callers of the superseded fetch complete with the newer result.- A cached read no longer cancels an in-flight forced refresh, and a cache hit no longer re-emits an identical value to the stream (1.1.0 always called
add). clearCache()andevict(key)discard results of fetches started before them (a logout can no longer be repopulated by a late response). Their callers complete with the fetch's own result, which is not cached; with a fetcher that honours the cancel signal (e.g. Dio) that is the fetcher's cancellation error.evict's pendinggetDatacompletes instead of hanging.- A storage read issued right after
evict/clearCacheis ordered behind the queued delete, so a deleted persisted entry never comes back (logout leak). updateData: a superseded, evicted, cleared or disposed update completes with its own result (it used to hang) and no longer emits an error or rolls back. A failed update rolls back only if nothing wrote the key since it started (a newerset/patch/fetch/update wins), and a fetch that started before the update no longer overwrites the optimistic value (its callers still get its result).invalidate,set,patch(andinvalidateWhere,invalidateAll,patchWhere,mutate) discard the result of an in-flight fetch without firing its cancel signal: callers waiting on it get its result instead of a cancellation error.- A throwing
errorMapperfalls back to the raw error, and a throwingerrorMapper/fetchFiltercan no longer leave a key's fetch stuck in flight. - Invalidating a watched key refetches it. A key is watched while its stream (
getStream,watch,watchState) has a listener;invalidate,invalidateWhere,invalidateAllandmutatenow refetch such keys immediately (errors only via the stream), like the paged manager. Unwatched keys are still only marked stale. A watched fetch in flight is detached as before (its callers get its result) and a new one starts (two requests in flight; the older one's response is discarded). invalidateWherealso matches keys that are being fetched or watched but have no cached value (it used to test cached keys only), so their in-flight results are discarded too.getStreamresolves the key's subject when it is listened to: a stream obtained before the key was evicted (or dropped bymaxEntries/evictAfterUnwatched) keeps working instead of replaying a closed subject. Calls for one key still return an equal stream (safe inStreamBuilder); withreplayErrors: falsethis is new.- The unused
asyncdependency was removed.
Compatibility notes #
- The public
fetcherfield became private; a deprecatedfetchergetter (Future<T> Function(K key)) is kept for 1.1.0 code. It calls the fetcher directly (no cache, no join); for a cancellable fetcher the cancel signal never fires. It will be removed in 3.0.0. getDatagained the named parametermaxAge: subclasses overridinggetDatamust add it.- About 20 new public members were added to
ReactiveDataManager; hand-writtenimplements ReactiveDataManagerfakes must implement them (generated mocks such as mocktail are unaffected). replayErrorsdefaults totrue(1.1.0 behaviour); exceptions and existing exports are unchanged.
Added — ReactiveDataManager / ReactiveValue #
maxAge(constructor and per call), injectableclock,fetchedAt(key),isFresh(key).invalidate(key)/invalidateWhere(test)/invalidateAll()— stale-while-revalidate: the value stays visible, in-flight results are discarded, watched keys refetch immediately. With storage they also apply to values restored later; only the 64 most recentinvalidateWherepredicates are retained, older ones are folded into a single marker that makes persisted values stored before it restore stale (at most one extra fetch, never a missed invalidation; keys already in memory are unaffected).refresh(key)— fire-and-forget refetch, errors only via the stream.prefetch(key)— fire-and-forget, non-forcedgetData: a no-op when fresh, joins a fetch in flight, errors only via the stream.watchState(key, {fetch})and the immutableDataState<T>(data,hasData,isLoading,error/stackTrace,fetchedAt,isStale,hasError,isLoadingInitial,errorAs<E>(); value equality): the previous data is kept while loading and after a failure, errors are state and never stream errors (nothing is replayed), equal states are not re-emitted, one operation emits one state. The stream survivesevict, closes ondispose, can be listened to several times and is the same object for the same arguments (B6).maxEntries(LRU over unwatched keys, at least 1,ArgumentErrorotherwise) andevictAfterUnwatched(timer cancelled by a re-watch). AnygetData/prefetch/refreshof an unwatched key counts as use: it restarts the timer and refreshes the key's LRU position. Automatic eviction frees memory only: an in-flight fetch is detached, persisted entries (and a pending invalidation of them) are kept. Explicitevictstill closes the key's subject.storageReadTimeout(also onReactiveValueandReactivePagedManager; defaultnull, no limit): a storage read slower than this counts as missing and its late result is dropped, so a stuck adapter never blocksgetData. The limit runs from the read request and includes the wait behind queued writes; a read that times out while queued never reaches the adapter.watch(key, {fetch})— non-nullStream<T>that fetches when missing or stale.mutate(key, action, {invalidate})— invalidates afterwards, also when the action fails.set(key, value)/patch(key, transform)/patchWhere(transform)— plain cache writes, no updater or rollback. An in-flight fetch is discarded so it cannot overwrite them.replayErrors: false— do not replay the last error to late subscribers.errorMapper— surfaces typed errors on the stream and fromgetData.ReactiveDataManager.cancellable— the fetcher receives anAbortSignal(the same type asPageRequest.signal) that is aborted when the fetch is superseded, evicted, cleared or disposed; wiresignal.whenAbortedto e.g. Dio'sCancelToken.ReactiveValue<T>— keyless single-value manager with the same API (includingprefetch()andwatchState());storageKey(default'value') lets several values share one storage adapter, andclear()deletes only that key.- Persistence:
ReactiveStorage,StoredEntry,InMemoryReactiveStorage,storage/storageVersionoptions (stale-while-revalidate across restarts).getData,watch(alsofetch: false) andgetStreamrestore a persisted value; storage errors (also synchronous throws) never fail a read; storage is never touched afterdispose().
Added — ReactivePagedManager<Q, T, C> #
Paginated lists, one accumulated list per query:
watch,peek,loadNext,loadPrevious,refresh({anchor, mode}); loading futures never throw or hang (also whenidOf, a replayed transform orpersistWhenthrows) and resolve to aPagedState.PagedState(items,hasLoaded,isRefreshing,refreshError,next/previousedges,totalCount,fetchedAt,isStale) with value equality, likePagedEdgeandPagedError; equal states are not re-emitted. Errors live in the state, never replayed as stream errors.- Opaque cursors (
PageRequest,PageResult,PageFetcher,PageDirection),AbortSignal(insidePageRequest),PageCursorExpiredException(always recovered with a first-page refresh). - Concurrent
loadNextjoins one request; loads started beforeinvalidate/refresh/evict/clearCachenever write their page; local edits made in flight are re-applied onto the response. - Dedupe by
idOf,loadedCount(also counting the raw items of followed all-duplicate pages within one call), unproductive-page and cursor-loop guards. patchItem/removeItemacross every cached query,upsertItem(head/tail,move; absent items only at a fully loaded end, never on unloaded or restored-only queries).invalidate/invalidateWhere/invalidateAll(a watched query refetches),evict,clearCache,dispose(laterevict/clearCacheare no-ops).prefetch(query)— fire-and-forget first-page load when nothing is loaded or the query is stale (invalidated, expired or restored from storage) and no head load runs; never throws.errorMapperwith the base manager's signature: errors thrown byfetchPageare mapped before they reachPagedErrorandonError; a throwing mapper falls back to the raw error, an expired cursor is recovered and never mapped.@visibleForTesting debugCursors(query):(next, previous, pages)record with the cursors the nextloadNext/loadPreviouswould send, ornullwhen the query is not cached.- A debug-build warning (
dart:developerlog, namereactive_data_manager) when an edge is given up aftermaxUnproductivePagesunproductive pages. - Eviction:
maxEntries(LRU over unwatched queries),evictAfterUnwatched,Retention.firstPage;maxAge,onError, injectableclock.maxEntries,maxItems,maxRefreshPagesandmaxUnproductivePagesmust be at least 1 (ArgumentError). RefreshMode.mergeHead/allPages,refresh(anchor:),maxItemswindowing,maxRefreshPages; exact per-page accounting so windowing andRetention.firstPagekeep working after splices and replayed edits.mutatewith optimisticPagedEditsand rollback,invalidateAfter.- Persistence of the first page (
storage,persistWhen,storageVersion,PagedSnapshot): stored page emitted first, revalidated;evict/clearCachedelete it. package:reactive_data_manager/testing.dartwithScriptedPageFetcher.
Changed (internal) #
ReactiveDataManager,ReactiveValueandReactivePagedManagerrun on a shared internal engine (lib/src/engine/): in-flight operations with abort signals and per-lane join/supersede, freshness against the injectable clock, the serialized storage queue with version checks, and the entry registry (watcher ref-count,maxEntriesLRU,evictAfterUnwatchedtimers).fake_asyncdev dependency relaxed to^1.3.1(Flutter 3.27).meta: ^1.12.0added as a dependency (for@visibleForTesting; the version pinned by Flutter 3.22, the declared SDK floor).- Error mapping lives in
lib/src/engine/errors.dart, shared by both managers.
Not implemented (from the design) #
- A debug assert for calls after
dispose. Both managers document calls afterdisposeas safe no-ops (evict/clearCacheon a disposed paged manager, memory-onlyevict/clearCacheon a disposed base manager, an idle state from paged loads), and existing tests rely on that; an assert would turn these documented no-ops into failures in debug builds, e.g. when widget teardown order callsevictafter the owner disposed the manager.
1.1.0 - 2026-09-01 #
Added #
- 🗑️
evict(key)— removes the cached value, subject, and any in-flight fetch/update for a single key, without resetting every other key the wayclearCache()does. Useful for callers that key by something derived (e.g. a request minus its pagination params) and need to drop one superseded entry while leaving the rest of the cache intact.
1.0.0 - 2025-01-10 #
Initial Release 🎉 #
Features
- ✨ Reactive data streams with RxDart integration
- 💾 Built-in caching system
- ⚡ Optimistic updates support
- 🔍 Configurable data filtering
- ❌ Comprehensive error handling
- 🧹 Automatic resource cleanup
- 📝 Type-safe API
- 🔄 Cancellable operations
Components
ReactiveDataManager- Core class for reactive data management- Data filtering capabilities
- Cache management
- Stream handling
- Error handling with custom exceptions
Dependencies
- RxDart for reactive streams
- Async package for cancellable operations
Documentation
- Comprehensive README with usage examples
- Fully documented API with examples
- Installation instructions