subscribe method

Future<RealmResults<T>> subscribe({
  1. String? name,
  2. WaitForSyncMode waitForSyncMode = WaitForSyncMode.firstTime,
  3. CancellationToken? cancellationToken,
  4. bool update = false,
})

Adds this RealmResults query to the set of active subscriptions. The query will be joined via an OR statement with any existing queries for the same type.

If a name is given this allows you to later refer to the subscription by name, e.g. when calling MutableSubscriptionSet.removeByName.

If update is specified to true, then any existing query with the same name will be replaced. Otherwise a RealmException is thrown, in case of duplicates.

WaitForSyncMode specifies how to wait or not wait for subscribed objects to be downloaded. The default value is WaitForSyncMode.firstTime.

The cancellationToken is optional and can be used to cancel the waiting for objects to be downloaded. If the operation is cancelled, a CancelledException is thrown and the download continues in the background. In case of using TimeoutCancellationToken and the time limit is exceeded, a TimeoutException is thrown and the download continues in the background.

{@category Sync}

Implementation

Future<RealmResults<T>> subscribe({
  String? name,
  WaitForSyncMode waitForSyncMode = WaitForSyncMode.firstTime,
  CancellationToken? cancellationToken,
  bool update = false,
}) async {
  final subscriptions = realm.subscriptions;
  Subscription? existingSubscription = name == null ? subscriptions.find(this) : subscriptions.findByName(name);
  late Subscription updatedSubscription;
  subscriptions.update((mutableSubscriptions) {
    updatedSubscription = mutableSubscriptions.add(this, name: name, update: update);
  });
  bool shouldWait = waitForSyncMode == WaitForSyncMode.always ||
      (waitForSyncMode == WaitForSyncMode.firstTime && subscriptionIsChanged(existingSubscription, updatedSubscription));

  return await CancellableFuture.from<RealmResults<T>>(() async {
    if (cancellationToken != null && cancellationToken.isCancelled) {
      throw cancellationToken.exception!;
    }
    if (shouldWait) {
      await subscriptions.waitForSynchronization(cancellationToken);
      await realm.syncSession.waitForDownload(cancellationToken);
    }
    return _SubscribedRealmResult._(this, subscriptionName: name);
  }, cancellationToken);
}