Event bus (real-time updates)

Use sdk.eventBus to receive conversation activity live: messages, conversation events and updates, and typing indicators for the conversations the signed-in person takes part in, plus occasional system broadcasts. It connects on first access and reconnects automatically after connection failures. On the same connection you can subscribe to domain events, as many subscriptions as you need: what happened to the data the caller may read (task.updated, homepage.post.updated and so on), narrowed by event type, company or entity. A signed-in person’s subscriptions are live; a machine client’s are durable, acknowledged and sent again until acknowledged. There are no webhooks. See Events on the developer portal.

Accessing the event bus

The examples assume a configured sdk from Getting started. In React, get it with useSoliboApi() inside a SoliboProvider.

Read sdk.eventBus after sign-in: the first read opens the connection at once, and a connection opened before sign-in is refused until a reconnect carries the new session.

SoliboSDK from the sdk artifact has eventBus as a member. On a client built from sdk-core alone (SoliboSDKBase), it is an extension property: add import no.solibo.oss.sdk.api.eventBus. In JavaScript, a client from the package root always has eventBus; a client from @solibo/solibo-sdk/core has it once the bundle imports @solibo/solibo-sdk/events (import '@solibo/solibo-sdk/events';), so pages that never use it leave the event bus, its WebSocket client and the event models out.

Subscribing to events

onEvent returns an unsubscribe function. Call it when the screen or component no longer needs updates.

Every onEvent listener gets every event, in the order they arrived, so each screen or feature can listen for itself. Events that arrive before the first listener wait for it.

Following the connection

The bus reconnects by itself and sends its subscriptions again. onConnectionChange tells a listener when the connection opens (true) and closes (false), and connected says how it is right now. Anything else the server keeps for one connection is gone after a reconnect: set it up again when onConnectionChange reports true. Like onEvent, it returns a function that stops the listener.

import no.solibo.oss.sdk.api.gen.models.ConversationMessagePayload

val unsubscribe = sdk.eventBus.onEvent { event ->
    val payload = event.payload
    if (payload is ConversationMessagePayload) {
        println("New message: ${payload.message.content}")
    }
}

// When leaving the screen:
// unsubscribe()
import { useEffect } from 'react';
import { ConversationMessagePayload } from '@solibo/solibo-sdk';
import { useSoliboApi } from '@solibo/solibo-react';

function ChatUpdates() {
  const { eventBus } = useSoliboApi();

  useEffect(() => eventBus.onEvent(({ payload }) => {
    if (payload instanceof ConversationMessagePayload) {
      console.log('New message:', payload.message.content);
    }
  }), [eventBus]);

  return null;
}

Sending commands

Besides the delivery commands below (Subscribe, Ack, Unsubscribe, which subscribe, ack and unsubscribe send for you), the bus accepts typing indicators and ping; a connection that never subscribes receives the conversation activity above. Use send in Kotlin or sendJs in TypeScript. For example, send a typing indicator:

import no.solibo.oss.sdk.api.gen.models.Typing

// Inside a coroutine:
sdk.eventBus.send(
    Typing(companyId = companyId, conversationId = conversationId, typing = true)
)
import { Typing } from '@solibo/solibo-sdk';

sdk.eventBus.sendJs(new Typing(BigInt(companyId), BigInt(conversationId), true));

Domain events

Connect once, then subscribe to what you need. Each subscribe(subscriptionKey, eventTypes, resume, afterSequence, maxInFlight, companyIds, entities) adds a subscription to the connection, up to 20; unsubscribe(subscriptionKey) ends one while the connection and the others go on. Subscribing again with a key you hold replaces that subscription. The bus sends every subscription again on each reconnect. A key matches ^[a-z0-9_-]{1,64}$.

Many subscriptions on one connection need a backend that carries them. An older backend keeps only the first subscription of a connection and refuses the others with ALREADY_SUBSCRIBED.

A subscription narrows what the caller may read over REST:

  • eventTypes: the backend’s names or their prefixes, such as "homepage.post.updated" or "homepage.".
  • companyIds: the event’s company. An event without a company never matches.
  • entities: an EventEntityRef(id = …, type = …) the event is about, or one it names among its related ids, so EventEntityRef(id = "12", type = "conversation") also matches the messages of conversation 12.

Leave a filter out to not narrow by it. Events arrive through onEvent as DomainEventPayload frames in seq order, each naming its subscriptionKey; an event that matches several of your subscriptions arrives once for each. An event names what changed and who changed it (event.type, event.entity, event.actor, event.changedFields, event.related), never the content: read the entity over REST. The type is a string, so a type newer than your SDK still arrives.

A SubscribedPayload confirms each subscription. A SubscriptionEndedPayload reports one that ended while the connection stays open, with its reason: UNSUBSCRIBED after your own unsubscribe (and, for a machine client, after a replacing subscribe; a person’s subscription is replaced without one), or the server’s reason. After ACK_TIMEOUT or CURSOR_RESET the bus subscribes again by itself. After SUPERSEDED (another connection took the key), CURSOR_EXPIRED or SUBSCRIPTION_DISABLED it drops the subscription, and subscribing again is up to you. An EventBusErrorPayload reports a refused command; a fatal one closes the connection. A refused subscribe (a key outside the pattern, a bad filter, a 21st subscription, a resume under another filter) carries its subscriptionKey, and the bus drops that subscription instead of sending it again on every reconnect.

When the server closes the connection soon after it opened, the bus waits before reconnecting, one second at first and doubling up to 30 seconds, until a connection lasts.

What a subscription keeps depends on who is signed in.

A person’s subscriptions are live only

A person (a browser or app session) gets the events they may read from the moment a subscription starts. Nothing is stored and nothing is sent again:

  • resume, afterSequence and maxInFlight are ignored.
  • There is nothing to acknowledge: ack is ignored, and redelivery is always false.
  • Events that happen while the connection is down are not sent later. After a reconnect, when onConnectionChange reports true, read the current state over REST.

A machine client’s subscriptions are durable

A machine client with the eventbus:connect grant keeps a cursor per subscriptionKey, at most 20 keys per client, in an event log the server retains for 14 days by default. Acknowledge what you have handled with ack(subscriptionKey, upTo) (every event up to upTo) or ack(subscriptionKey, sequences = …). A subscription that stops acknowledging is ended with ACK_TIMEOUT and subscribed again, and events sent but not acknowledged come again with redelivery set, so make handling idempotent by event.eventId.

  • The server keeps the cursor under the key together with its filter. Resuming a key with a different filter is refused: subscribe with FROM_HEAD or use another key.
  • resume picks where the first connection starts: AFTER_ACKED (the default cursor), AFTER_SEQUENCE with afterSequence, or FROM_HEAD for new events only. Later reconnects resume after the acknowledged cursor. maxInFlight caps events sent but not yet acknowledged.
  • AckedPayload, ReplayCompletePayload and HeartbeatPayload report the subscription’s state. CURSOR_EXPIRED means the cursor is older than the events the server keeps: reload over REST, then subscribe again with FROM_HEAD.

For example, one connection following the tasks feed and one homepage post. A person’s app makes the same calls and leaves out ack.

import no.solibo.oss.sdk.api.gen.models.DomainEventPayload
import no.solibo.oss.sdk.api.gen.models.EventEntityRef

sdk.eventBus.onEvent { event ->
    val payload = event.payload
    if (payload is DomainEventPayload) {
        refresh(payload.event.entity)
        sdk.eventBus.ack(payload.subscriptionKey, upTo = payload.seq)
    }
}
sdk.eventBus.subscribe("tasks", eventTypes = arrayOf("task."))
sdk.eventBus.subscribe("post-8", entities = arrayOf(EventEntityRef(id = "8", type = "homepagePost")))
import { DomainEventPayload, EventEntityRef } from '@solibo/solibo-sdk';

eventBus.onEvent(({ payload }) => {
  if (payload instanceof DomainEventPayload) {
    refresh(payload.event.entity);
    eventBus.ack(payload.subscriptionKey, payload.seq);
  }
});
eventBus.subscribe('tasks', ['task.']);
eventBus.subscribe('post-8', null, null, null, null, null, [new EventEntityRef('8', 'homepagePost')]);

In React

@solibo/solibo-react/events subscribes for a component while it is mounted, each component with a subscription key of its own on the shared connection:

  • useDomainEvents({ eventTypes, companyIds, entities, enabled, onEvent, onReconnect }) calls onEvent with the matching DomainEventPayload frames. onReconnect is called when the connection comes back after it was open for the subscription, not on the first connection: a person’s subscriptions are live only, so read the current state again there.
  • useLiveHomepage(companyId) keeps a company’s homepage on screen current: when a post or practical information changes, also while someone types in a co-edited one, and after a reconnect, it reads that company’s feed, posts, practical information, homepage and attachments again, once a second after the last change of a burst and at least every five seconds while it lasts.
import { useLiveHomepage } from '@solibo/solibo-react/events';

useLiveHomepage(companyId);

Editing a text together

A rich-text body can be edited by several people at once as a shared text, such as a homepage post or practical information. The backend relays the editors’ Yjs updates over the event bus and saves the result to the owner. Two entries make this available without pulling Yjs into bundles that do not use it; both need yjs installed.

  • @solibo/solibo-react/shared-text has useSharedText. It returns what the solibo-ui Editor takes as collaboration, or undefined when the body is to be edited on its own: when switched off with enabled, before the owner exists, or when the person may not edit the shared text. onReplaced is called when the body was saved by someone outside the shared text; the editor has then already started over from the new body. onUnavailable(problem) is called when editing together stops for the owner and the body is edited on its own again, so the person can be told that others’ typing no longer reaches them.
  • @solibo/solibo-query/shared-text has the connector underneath, SharedTextProvider, and createSharedTextTransport, which carries it over an EventBus. It depends on neither React nor Lexical.
import { useSharedText } from '@solibo/solibo-react/shared-text';
import { Editor } from '@solibo/solibo-ui';

const collaboration = useSharedText({
  companyId,
  editor: user,
  enabled: coEditingAvailable,
  onReplaced: () => showToast('The text was changed elsewhere and has been reloaded.'),
  onUnavailable: () => showToast('Editing together is not available right now.'),
  ownerId: post.id,
  ownerType: 'HOMEPAGE_POST',
});

return <Editor collaboration={collaboration} content={post.content} onChange={setContent} />;

While collaboration is set, save the owner’s other fields without its body: the backend saves the body itself as people type.

Error handling

Subscribe to connection and decoding errors with onError. It also returns an unsubscribe function. onError also reports decode error: … for payload types newer than your SDK; those events are dropped, and the connection stays up.

val unsubscribeErrors = sdk.eventBus.onError { error ->
    println("Event bus error: $error")
}
const unsubscribeErrors = sdk.eventBus.onError((error) => {
  console.error('Event bus error:', error);
});

Connection lifecycle

Unsubscribing removes a listener without closing the shared connection. Use eventBus.stop() only when disposing of the SDK; it permanently closes that event bus. Call it from a Kotlin coroutine or await it in TypeScript. Create a new SDK instance if you need a connection afterward.

See the AsyncAPI viewer for available messages and commands, or download the AsyncAPI definition.


Solibo AS