declareBackgroundLivelinessSubscriber method

Stream<Sample> declareBackgroundLivelinessSubscriber(
  1. Object keyExpr, {
  2. bool history = false,
  3. bool retainPayload = false,
})

Declares a fire-and-forget background subscriber on liveliness tokens intersecting keyExpr.

Returns a Stream of Samples: a SampleKind.put when a liveliness token is declared and a SampleKind.delete when it is undeclared or lost. Unlike declareLivelinessSubscriber, there is no handle; the stream completes automatically when this session is closed.

If history is true, the subscriber also replays liveliness tokens that were already alive before the subscription was declared.

⚠️ This stream is UNBOUNDED, and pausing it does not stop the flow — see declareSubscriber for the measurement. No bounded form exists here either, and for the same reason: a background declaration hands back no handle. Use declarePullLivelinessSubscriber when you need a bound.

Throws ZenohException if the key expression is invalid. Throws StateError if the session has been closed.

Implementation

Stream<Sample> declareBackgroundLivelinessSubscriber(
  Object keyExpr, {
  bool history = false,

  /// See [declareSubscriber] for what `retainPayload` costs and promises.
  bool retainPayload = false,
}) {
  return _withKeyExprArg(keyExpr, 'keyExpr', (loanedSession, loanedKe) {
    // ALLOCATE-LAST: no open ReceivePort survives a rejected key expression.
    final channel = Subscriber.createSampleChannel(
      retainPayload: retainPayload,
    );

    final rc = bindings.zd_liveliness_declare_background_subscriber(
      loanedSession.cast(),
      loanedKe.cast(),
      channel.receivePort.sendPort.nativePort,
      history ? 1 : 0,
      retainPayload ? 1 : 0,
    );

    if (rc != 0) {
      channel.abandon();
      throw ZenohException(
        'Failed to declare background liveliness subscriber',
        rc,
      );
    }

    return channel.stream;
  });
}