attachToServices method

void attachToServices()

Hooks the running listener onto whichever of the client's sync and notification services are set, once each, so a service set after startListening is attached too; a no-op before it and after stopListening.

Implementation

void attachToServices() {
  final listener = _syncListener;
  final addresses = _listeningFor;
  if (listener == null || addresses == null) return;
  // Best effort, because this runs inside the client's service setters and a
  // client must come up whether or not its envelope listener did.
  if (_listeningTo == null) {
    try {
      final sync = _serviceIfSet(() => atClient.syncService);
      if (sync != null) {
        _listeningTo = sync;
        sync.addProgressListener(listener);
      }
    } catch (e) {
      logSwallowed(
          logger,
          e,
          'Could not attach the envelope listener to sync for '
          '${atClient.getCurrentAtSign()}; envelopes delivered by sync will '
          'wait for the next periodic sweep: $e');
    }
  }
  if (_wakeUpSubscription == null) {
    try {
      final notifications = _serviceIfSet(() => atClient.notificationService);
      if (notifications != null) {
        // A wake-up notification only nudges us; the envelope itself is
        // fetched from the atServer (a sync-less client has no local copy),
        // so the sweep it triggers reads remote.
        _wakeUpSubscription = notifications
            .subscribe(
                regex: EnvelopeAddressing.regexForAny(addresses),
                shouldDecrypt: false)
            .listen((_) => _sweepInBackground(fromRemote: true));
      }
    } catch (e) {
      logSwallowed(
          logger,
          e,
          'Could not subscribe to envelope wake-ups for '
          '${atClient.getCurrentAtSign()}; envelopes will wait for sync or '
          'the next periodic sweep: $e');
    }
  }
}