Skip to content

Commit

Permalink
Add assert that callback to write is not async
Browse files Browse the repository at this point in the history
  • Loading branch information
nielsenko committed May 6, 2024
1 parent b42fe15 commit 7e91fb4
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/realm_dart/lib/src/realm_class.dart
Original file line number Diff line number Diff line change
Expand Up @@ -346,11 +346,14 @@ class Realm implements Finalizable {
/// Checks whether the `Realm` is in write transaction.
bool get isInTransaction => realmCore.getIsWritable(this);

bool _isSubtype<S, T>() => <S>[] is List<T>;

/// Synchronously calls the provided callback inside a write transaction.
///
/// If no exception is thrown from within the callback, the transaction will be committed.
/// It is more efficient to update several properties or even create multiple objects in a single write transaction.
T write<T>(T Function() writeCallback) {
assert(!_isSubtype<T, Future>(), 'writeAsync should be used for async operations');
final transaction = beginWrite();

try {
Expand Down
5 changes: 5 additions & 0 deletions packages/realm_dart/test/realm_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1269,6 +1269,11 @@ void main() {
expect(realm.all<Person>().length, 0); // everything is rolled back
});

test('Realm.write with async callback', () {
final realm = getRealm(Configuration.local([Person.schema]));
expect(() => realm.write(() async {}), throwsA(isA<AssertionError>()));
});

test('Transaction.commitAsync with a canceled token throws', () async {
final realm = getRealm(Configuration.local([Person.schema]));

Expand Down

0 comments on commit 7e91fb4

Please sign in to comment.