cell_memory 1.0.3
cell_memory: ^1.0.3 copied to clipboard
Durable memory cells for the Cell framework. File store. No Flutter.
// Copyright (c) 2025-Present Lee Man Hoi Simon. See the AUTHORS file
// for details. Use of this source code is governed by a MIT or
// Apache-2.0 license that can be found in the LICENSE file.
//
// SPDX-License-Identifier: MIT OR Apache-2.0
/// The walk-through example for `cell_memory`: a counter that survives
/// a process restart through a [MemoryStore].
///
/// Run from `packages/cell_memory`:
///
/// dart run example/cell_memory.dart
library;
import 'package:cell/cell.dart';
import 'package:cell_memory/cell_memory.dart';
Future<void> main() async {
// 1. The reactive source of truth. `Cell.state` returns a handle whose
// `cell` is safe to share; the mutation functions stay with you.
final counter = Cell.state<int>(initial: 0);
// 2. Attach durability. `rememberState` opens a [MemoryCell] bound to
// the record id `'counter'` and hydrates the state cell from the
// store; every accepted mutation is then written through per the
// [MemoryStrategy] (immediate by default).
final store = InMemoryMemoryStore();
final memory = await rememberState<int>(
counter,
record: MemoryRecord<int>(
id: 'counter',
store: store,
codec: JsonMemoryCodec<int>.identity(),
),
);
// 3. Ordinary mutations persist without any extra bookkeeping.
counter.update(41);
// 4. `save` settles a scheduled write; `close` flushes once and
// releases the cell. The default infrastructure does not own the
// store, so it stays usable for the next process "restart".
await memory.save();
print('saved: counter=${counter.cell.value} '
'(snapshot revision ${memory.snapshot.revision})');
await memory.close();
// 5. Reopen on the same record: the stored value is hydrated back
// into the state cell.
final resumed = await rememberState<int>(
counter,
record: MemoryRecord<int>(
id: 'counter',
store: store,
codec: JsonMemoryCodec<int>.identity(),
),
);
print('after reopen: counter=${counter.cell.value}');
await resumed.close();
}