init method

  1. @override
Future<void> init()
override

Public APIs to be implemented by any Persistor extension like FilePersistor.

Initialization function called when the persistor is instantiated to execute and setup work.

Implementation

@override
init() async {
  final [encrypter, directory] = await Future.wait([
    initEncrypter(),
    initDirectory(),
  ]);

  // Create a receive port on the main isolate to receive messages from the worker.
  _receivePort = ReceivePort();
  _receivePort.listen(_onMessage);

  // The initial message request to the worker contains three necessary values:
  // 1. The persistor's send port that will allow for message passing from the worker.
  // 2. The directory that the worker uses to persist file data stores.
  // 3. The encrypter used by file data stores that have encryption enabled.
  final initMessage = InitMessageRequest(
    sendPort: _receivePort.sendPort,
    directory: directory as Directory,
    encrypter: encrypter as Encrypter,
    persistenceThrottle: persistenceThrottle,
    settings: settings,
  );

  final completer =
      _messageRequestIndex[initMessage.id] = Completer<InitMessageResponse>();

  try {
    await _logger.measure('Worker spawn', () async {
      return Isolate.spawn(
        FilePersistorWorker.init,
        initMessage,
        debugName: 'Loon worker',
      );
    });

    final response = await completer.future;
    _sendPort = response.sendPort;
  } catch (e) {
    _logger.log("Worker initialization failed.");
    _receivePort.close();
    rethrow;
  }
}