Skip to content

Instantly share code, notes, and snippets.

@mattrussell-sonocent
Last active June 7, 2022 12:50
Show Gist options
  • Save mattrussell-sonocent/6550c4c11185b99a8e22eec556c21361 to your computer and use it in GitHub Desktop.
Save mattrussell-sonocent/6550c4c11185b99a8e22eec556c21361 to your computer and use it in GitHub Desktop.
Zone values for transaction propagation
import 'dart:async';
import 'dart:math';
import 'package:sembast/sembast.dart';
import 'package:sembast/sembast_io.dart';
Future<void> main() async {
final dbPath = 'sample-${Random().nextInt(10000)}.db';
final dbFactory = databaseFactoryIo;
final db = await dbFactory.openDatabase(dbPath);
final transactionManager= TransactionManager(db);
final eventStore = EventStore(db, transactionManager);
// Successful transaction:
await transactionManager.transaction(() async {
await eventStore.put('event1', '{ "id": "event1" }');
});
print(await eventStore.get('event1'));
// Aborted transaction:
try {
await transactionManager.transaction(() async {
await eventStore.put('event2', '{ "id": "event2" }');
throw AssertionError('no more db for you');
await eventStore.put('event3', '{ "id": "event3" }');
});
} catch (e) {
print("Expected error occurred");
}
print(await eventStore.get('event2')); // => null
}
class EventStore {
Database db;
TransactionManager transactionManager;
StoreRef<String, String> store = StoreRef.main();
EventStore(this.db, this.transactionManager);
Future<void> put(String eventId, String json) async {
final tx = transactionManager.currentTransaction();
await store.record(eventId).put(tx, json);
}
Future<String?> get(String eventId) => store.record(eventId).get(db);
}
class TransactionManager {
Database db;
TransactionManager(this.db);
Future<T> transaction<T>(Future<T> Function() f) async {
return await db.transaction((tx) async {
return await runZoned(() async {
return await f();
}, zoneValues: {'tx': tx});
});
}
Transaction currentTransaction() => Zone.current['tx'] as Transaction;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment