open static method

Future<Realm> open(
  1. Configuration config, {
  2. CancellationToken? cancellationToken,
  3. ProgressCallback? onProgressCallback,
})

A method for asynchronously opening a Realm.

When the configuration is FlexibleSyncConfiguration, the realm will be downloaded and fully synchronized with the server prior to the completion of the returned Future. This method could be called also for opening a local Realm with LocalConfiguration.

  • config- a configuration object that describes the realm.
  • cancellationToken - an optional CancellationToken used to cancel the operation.
  • onProgressCallback - a callback for receiving download progress notifications for synced Realms.

Returns Future<Realm> that completes with the Realm once the remote Realm is fully synchronized or with a CancelledException if operation is canceled. When the configuration is LocalConfiguration this completes right after the local Realm is opened. Using Realm.open for opening a local Realm is equivalent to using the constructor of Realm.

Implementation

static Future<Realm> open(Configuration config, {CancellationToken? cancellationToken, ProgressCallback? onProgressCallback}) async {
  if (cancellationToken != null && cancellationToken.isCancelled) {
    throw cancellationToken.exception!;
  }

  if (config is! FlexibleSyncConfiguration) {
    final realm = Realm(config);
    return await CancellableFuture.value(realm, cancellationToken);
  }

  _ensureDirectory(config);

  final asyncOpenHandle = realmCore.createRealmAsyncOpenTask(config);
  return await CancellableFuture.from<Realm>(() async {
    if (cancellationToken != null && cancellationToken.isCancelled) {
      throw cancellationToken.exception!;
    }

    StreamSubscription<SyncProgress>? progressSubscription;
    if (onProgressCallback != null) {
      final progressController = RealmAsyncOpenProgressNotificationsController._(asyncOpenHandle);
      final progressStream = progressController.createStream();
      progressSubscription = progressStream.listen(onProgressCallback);
    }

    late final RealmHandle realmHandle;
    try {
      realmHandle = await realmCore.openRealmAsync(asyncOpenHandle, cancellationToken);
      return Realm._(config, realmHandle);
    } finally {
      await progressSubscription?.cancel();
    }
  }, cancellationToken, onCancel: () => realmCore.cancelOpenRealmAsync(asyncOpenHandle));
}