nexus
Core guides

Connection Lifecycle

Observe connections, respond to identity changes, and replace disconnected handles.

A Connection is a shared session handle. Keep the handle used to acquire your service when the application needs to observe its lifetime.

Observe Existing And New Connections

Use onConnect to initialize each current or future ready session once:

import { DocumentToken } from "./shared";

const stopObserving = app.onConnect((connection) => {
  const acquired = connection.safeGet(DocumentToken);
  if (acquired.isErr()) {
    console.error(connection.id, acquired.error.code);
    return;
  }

  const stopDisconnect = connection.onDisconnected((reason) => {
    markSourceOffline(connection.id, reason);
  });

  void acquired.value.summarize("intro").then(
    (summary) => {
      if (connection.status === "connected") {
        showSummary(connection.id, summary);
      }
    },
    (error) => console.error(connection.id, error),
  );

  // Application bookkeeping ends these listeners if the view closes first.
  registerViewCleanup(stopDisconnect);
});

app is configured; markSourceOffline, showSummary, and registerViewCleanup belong to the application’s view. Stopping stopObserving prevents future deliveries, but does not undo initialization or stop listeners already registered inside it.

For selected peers use app.onConnect(matchesSource, listener). A subscription delivers each session at most once, including when an identity update makes a previously unmatched session eligible. The listener can be registered before bootstrap; it does not initiate dialing or wait for a particular service.

Observe One Session’s Identity

Use subscribeIdentity when behavior depends on changes within the same session:

let wasReady = false;

const stopIdentity = connection.subscribeIdentity((meta) => {
  const ready = isDocumentSourceReady(meta);
  if (ready && !wasReady) {
    void initializeSource(connection).catch(console.error);
  }
  wasReady = ready;
});

The application defines isDocumentSourceReady and initializeSource. The listener immediately receives the current full identity, then each accepted full update, even when values are equal. It ends on disconnect; a subscription to an already disconnected handle receives no identity delivery.

The framework does not select fields or serialize asynchronous application work. Returned cleanup functions are not invoked. See Identity and metadata for declaring fields.

Publish Before Announcing Business Readiness

When a provider depends on asynchronous setup, publish it first, then update an application-defined ready field:

app.provide(DocumentToken, documents);
await app.updateIdentity({ documentsReady: true });

Declare documentsReady in your context metadata model. A peer using onConnect(matchesReadySource, listener) can then initialize the session once. For repeated ready/unready transitions, use subscribeIdentity instead.

On the same live session, the earlier catalog update is applied before the later identity notification. updateIdentity completion is not an acknowledgement that every peer has run its application listener. Readiness is a business declaration; get still checks the real catalog.

Handle Disconnection

connection.status is "connected" or "disconnected". onDisconnected delivers one terminal reason per subscription, including late subscribers. Reasons are "local", "remote", and "protocol".

Disconnect removes the session from routing and clears its pending calls and communication resources before normal public disconnect notification. Business cleanup remains application-owned. A rejected business call by itself does not disconnect the session.

After disconnect, acquire a new connection and get a fresh proxy:

const replacement = await app.connect({ target });
const documents = replacement.get(DocumentToken);

Prevent old asynchronous work from updating a replacement view by associating results with their connection or an application lifecycle revision. Nexus does not automatically retry, retarget handles, or replay methods.

End A Shared Session Deliberately

connection.disconnect();

This is idempotent and affects every local user of that session. It does not wait for remote business acknowledgement. Dropping a handle, a collection, or a root service proxy does not close the session. A view that only needs to stop observing should cancel its subscriptions and release its own refs instead.

Edit this page on GitHub