Last active
June 7, 2022 12:50
-
-
Save mattrussell-sonocent/6550c4c11185b99a8e22eec556c21361 to your computer and use it in GitHub Desktop.
Zone values for transaction propagation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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