Store.fromReference constructor

Store.fromReference(
  1. ModelDefinition modelDefinition,
  2. ByteData _reference, {
  3. bool queriesCaseSensitiveDefault = true,
})

Create a Dart store instance from an existing native store reference.

Use this if you want to access the same store from multiple isolates. This results in two (or more) isolates having access to the same underlying native store. Concurrent access is ensured using implicit or explicit transactions.

Note: make sure you don't use store in any of the isolates after the original store is closed (by calling close).

To do this, you'd send the reference over a SendPort, receive it in another isolate and pass it to Store.fromReference.

Example:

// See test/isolates_test.dart for an actual working example.
// Main isolate:
  final store = Store(getObjectBoxModel())

...

// use the sendPort of another isolate to send an open store reference.
  sendPort.send(store.reference);

...

// receive the reference in another isolate
  Store store;
  // Listen for messages
  await for (final msg in port) {
    if (store == null) {
      // first message data is existing Store's reference
      store = Store.fromReference(getObjectBoxModel(), msg as ByteData);
    }
    ...
  }

Implementation

Store.fromReference(ModelDefinition modelDefinition, this._reference,
    {bool queriesCaseSensitiveDefault = true})
    :
      // Must not close native store twice, only original store is allowed to.
      _closesNativeStore = false,
      _absoluteDirectoryPath = '' {
  // see [reference] for serialization order
  final readPid = _reference.getUint64(0 * _int64Size);
  if (readPid != pid) {
    throw ArgumentError("Reference.processId $readPid doesn't match the "
        'current process PID $pid');
  }

  _cStore = Pointer.fromAddress(_reference.getUint64(1 * _int64Size));
  if (_cStore.address == 0) {
    throw ArgumentError.value(_cStore.address, 'reference.nativePointer',
        'Given native pointer is empty');
  }

  _attachConfiguration(
      _cStore, modelDefinition, '', queriesCaseSensitiveDefault);
}