Begin Here

KOS Topic Handlers

Introduction

As part of the flow described previously, KOS models will typically use a "baseline and delta" approach where the model initially loads data as part of the load or activate lifecycle hooks and keeps in sync as the backend sends model deltas as WebSocket events that can be merged into the model in near real-time.

The KOS UI SDK provides a mechanism to register handlers for topics as part of the KOS Model.

@kosTopicHandler

The KOS SDK provides a decorator to register a model method as a topic handler. The handler will be invoked whenever the backend publishes an event on the provided topic.

In the following example, a model method is decorated with a kosTopicHandler annotation that includes the topic to be subscribed to as well as whether the handler should subscribe to WebSocket events or just general EventBus messages.

For more information on the TODO[EventBus] please review the additional documentation.

// src/models/demo/demo-model.ts

import {kosModel, kosTopicHandler} from "@coca-cola/kos-ui-core";

...

@kosTopicHandler({
    topic: "/demo/update",
    websocket: true
})
handleUpdate(data: ApiCallback) {
    log.info("update received");
    const body: {update: number} = JSON.parse(data.body);
    this.lastUpdate = body.update;
}

Conditional Topic Handlers

In cases where your model only needs to conditionally respond to messages on a topic, there is an additional condition parameter that can be passed into the decorator that accepts a function to determine if the message should be handled by the topic handler or not.

The condition function will receive both the message payload and the current model as parameters in order to determine if the message is relevant to the current instance of the model.

/**
 * Condition that checks whether an update received from the server corresponds to the current model.
 * Used as a short circuit to reduce unnecessary processing of handlers.
 *
 * @param apiKey - the response payload from the server
 * @param model - the  model to be compared
 * @returns true if the updated server response has the same id as the current model
 */
const verifyUpdatedApiKey = (apiKey: ApiKeyResponse, model: IApiKeyModel) =>
  model.id === apiKey.id;

@kosTopicHandler({
    topic: "/studioServer/apiKey/update",
    condition: verifyUpdatedApiKey,
  })
  handleApiKeyUpdated(data: ApiCallback) {
    const apiKey: ApiKeyResponse = JSON.parse(data.body);
    // update model with data
  }
}

Targeting a model-specific topic (KOS_MODEL_ID token)

In cases where the subscribed topic needs to be scoped to the current model, make use of the KOS_MODEL_ID token in your topic. When applied to the topic, the KOS_MODEL_ID token will be substituted with the current model ID at the time of topic subscription.

As a result, any message published to the topic including the model ID will be received ONLY by the single model instance.

For example, in the code below, assuming that there are two instances of the Demo model with id’s demo1 and demo2, each instance of the model will subscribe to the following topics:

model ID topic

demo1

/demo/update/demo1

demo2

/demo/update/demo2

import {kosTopicHandler, KOS_MODEL_ID} from "@coca-cola/kos-ui-core";

...

    @kosTopicHandler({
        topic: `/demo/update/${KOS_MODEL_ID}`,
        websocket: true
    })
    handleUpdate(data: ApiCallback) {
        log.info("update received");
        const body: {update: number} = JSON.parse(data.body);
        this.lastUpdate = body.update;
    }

Setting up the Mock Handler to Send Messages

In order to test that your topic handlers are wired up properly, especially in the absence of a functioning backend, use the sendToTopic utility found in the @coca-cola/kos-test-utils library.

The sendToTopic utility will simulate a message being sent from the backend to a specific topic.

In the following example, the sendToTopic call is placed inside a sendInterval block to simulate a call coming from the backend continually. This could just as easily be incorporated into a new component that can trigger the message as part of a manual action such as a button click or other operation.

// src/mockHandlers.ts

import { sendToTopic } from "@coca-cola/kos-test-utils";

/**
 * this is just for demonstration purposes to show continual updates that can be
 * received by topic handlers for a model.
 *
 * The sendToTopic function can be used to simulate web socket responses from the backend.
 */
setInterval(() => {
  sendToTopic("/demo/update", {
    headers: {},
    body: { update: Date.now() },
  });
}, 3000);

Cleaning up

The KOS framework will automatically clean up any subscriptions as models are removed from the model cache or as models go offline for any reason.

Subscriptions will be unsubscribed when:

  1. a model (or one of its parents) is destroyed via the destroyKosModel call in @coca-cola/kos-ui-core

  2. a model goes offline. The subscriptions will be re-applied once the model comes back online

Previous
Next
On this page
Java Development
Seamlessly transition from Legacy+ systems to Freestyle microdosing and advanced distributed dispense systems.
UI Development
Using KOS SDKs, integrating Consumer and Non-consumer facing UIs becomes seamless, giving you less hassle and more time to create.
Video Library
Meet some of our development team, as they lead you through the tools, features, and tips and tricks of various KOS tools.
Resources
Familiarize yourself with KOS terminology, our reference materials, and explore additional resources that complement your KOS journey.
Copyright © 2024 TCCC. All rights reserved.