Just a second...

Subscribe to recordV2 topics

The following example demonstrates how to process information from subscribed recordV2 topics, including the use of a schema.

This example demonstrates a Java™ client consuming recordV2 topics which contain currency conversion rates.

Each topic contains a record with two decimal fields, representing the buy and sell rates between a pair of currencies.

The example can be run either with or without a schema.

JavaScript
import * as diffusion from 'diffusion';

async function recordV2Subscribing() {
    const session = await diffusion.connect({
        host : 'host_name',
    });

    // the schema must match the one used when the topic was created
    const schema = diffusion.datatypes.recordv2().schemaBuilder()
        .record('Record').string('myString').integer('myInt').decimal('myDouble', 3)
        .build();

    session
        .addStream('my/topic/path', diffusion.datatypes.recordv2())
        .on('value', (topic, specification, newValue, oldValue) => {
            // the schema can be used to produce a model that allows key-based lookup of fields
            const model = newValue.asModel(schema);

            const myString = model.get('myString');
            const myInt = model.get('myInt');
            const myDouble = model.get('myDouble');

            console.log(`myString: ${myString}, myInt: ${myInt}, myDouble: ${myDouble}`);

            // if the schema is not known, it is possible to iterate across the received records and fields
            for (const record of newValue.asRecords()) {
                for (const field of record) {
                    console.log(`Field value: ${field}`);
                }
            }
        });

    session.select('my/topic/path');
}
.NET
/**
 * Copyright © 2026 DiffusionData Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System.Threading.Tasks;
using PushTechnology.ClientInterface.Client.Callbacks;
using PushTechnology.ClientInterface.Client.Factories;
using PushTechnology.ClientInterface.Client.Features.Topics;
using PushTechnology.ClientInterface.Client.Topics.Details;
using PushTechnology.ClientInterface.Data.Record;
using PushTechnology.ClientInterface.Data.Record.Schema;
using static System.Console;

namespace PushTechnology.ClientInterface.Example {
    /// <summary>
    /// Client subscribing to and processing values from a RecordV2 topic, using a schema.
    /// </summary>
    public sealed class RecordV2Subscribing {
        public async Task RecordV2SubscribingExample(string serverUrl)
        {
            var session = Diffusion.Sessions.Open(serverUrl);

            var recordStream = new RecordStream();
            session.Topics.AddStream("my/topic/path", recordStream);

            await session.Topics.SubscribeAsync("my/topic/path");
        }

        /// <summary>
        /// Basic implementation of the IValueStream for RecordV2 topics.
        /// </summary>
        private sealed class RecordStream : IValueStream<IRecordV2> {
            private ISchema schema;

            public void OnClose()
                => WriteLine("The subscription stream is now closed.");

            public void OnError(ErrorReason errorReason)
                => WriteLine($"An error has occured : {errorReason}.");

            public void OnSubscription(string topicPath, ITopicSpecification specification)
            {
                WriteLine($"Client subscribed to topic '{topicPath}'.");

                // retrieve the schema from the topic properties when subscribing
                var schemaJson = specification.Properties[TopicSpecificationProperty.SCHEMA];
                schema = Diffusion.DataTypes.RecordV2.ParseSchema(schemaJson);
            }

            public void OnUnsubscription(string topicPath, ITopicSpecification specification,
                                         TopicUnsubscribeReason reason)
                => WriteLine($"Client unsubscribed from topic '{topicPath}' with reason '{reason}'.");

            public void OnValue(string topicPath, ITopicSpecification specification, IRecordV2 oldValue,
                                IRecordV2 newValue)
            {
                // use the schema to produce a model that allows key-based lookup of fields
                var model = newValue.AsModel(schema);
                WriteLine($"myString: {model.Get("myString")}, myInt: {model.Get("myInt")}, " +
                          $"myDouble: {model.Get("myDouble")}.");

                if (oldValue != null)
                {
                    // generate a structural delta to determine what has changed
                    var delta = newValue.Diff(oldValue);
                    foreach (var change in delta.Changes(schema))
                    {
                        WriteLine($"Field '{change.FieldName}' changed to '{model.Get(change.FieldName)}'.");
                    }
                }
            }
        }
    }
}
Java and Android
/*******************************************************************************
 * Copyright (C) 2017, 2023 DiffusionData Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.pushtechnology.client.sdk.manual;

import static java.util.Objects.requireNonNull;

import com.pushtechnology.diffusion.client.Diffusion;
import com.pushtechnology.diffusion.client.features.Topics;
import com.pushtechnology.diffusion.client.features.Topics.UnsubscribeReason;
import com.pushtechnology.diffusion.client.features.Topics.ValueStream;
import com.pushtechnology.diffusion.client.session.Session;
import com.pushtechnology.diffusion.client.topics.details.TopicSpecification;
import com.pushtechnology.diffusion.datatype.recordv2.RecordV2;
import com.pushtechnology.diffusion.datatype.recordv2.RecordV2Delta;
import com.pushtechnology.diffusion.datatype.recordv2.RecordV2Delta.Change;
import com.pushtechnology.diffusion.datatype.recordv2.model.RecordModel;
import com.pushtechnology.diffusion.datatype.recordv2.schema.Schema;
import com.pushtechnology.diffusion.datatype.recordv2.schema.SchemaParseException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * This demonstrates a client consuming RecordV2 topics.
 * <P>
 * It has been contrived to demonstrate the various techniques for Diffusion
 * record topics and is not necessarily realistic or efficient in its
 * processing.
 * <P>
 * It can be run using a schema or not using a schema and demonstrates how the
 * processing could be done in both cases.
 * <P>
 * This makes use of the 'Topics' feature only.
 * <P>
 * To subscribe to a topic, the client session must have the 'select_topic' and
 * 'read_topic' permissions for that branch of the topic tree.
 * <P>
 * This example receives updates to currency conversion rates via a branch of
 * the topic tree where the root topic is called "FX" which under it has a topic
 * for each base currency and under each of those is a topic for each target
 * currency which contains the bid and ask rates. So a topic FX/GBP/USD would
 * contain the rates for GBP to USD.
 * <P>
 * This example maintains a local map of the rates and also notifies a listener
 * of any rates changes.
 *
 * @author DiffusionData Limited
 */
public final class RecordV2Subscribing {

    private static final Logger LOG =
        LoggerFactory.getLogger(RecordV2Subscribing.class);

    private static final String ROOT_TOPIC = "FX";

    /**
     * The map of currency codes to currency objects which each maintain rates
     * for each target currency.
     */
    private final Map<String, Currency> currencies = new ConcurrentHashMap<>();

    private Schema schema;

    private final RatesListener listener;

    private final Session session;

    /**
     * Constructor.
     *
     * @param serverUrl for example "ws://diffusion.example.com:80"
     * @param listener a listener that will be notified of all rates and rate
     *        changes
     */
    public RecordV2Subscribing(String serverUrl,
        RatesListener listener) {

        this.listener = requireNonNull(listener);

        session =
            Diffusion.sessions().principal("client").password("password")
                .open(serverUrl);

        // Use the Topics feature to add a record value stream and subscribe to
        // all topics under the root.
        final Topics topics = session.feature(Topics.class);
        final String topicSelector = String.format("?%s//", ROOT_TOPIC);

        topics.addStream(
            topicSelector,
            RecordV2.class,
            new RatesValueStream());

        topics.subscribe(topicSelector)
            .whenComplete((voidResult, exception) -> {
                if (exception != null) {
                    LOG.info("subscription failed", exception);
                }
            });
    }

    /**
     * Returns the rates for a given base and target currency.
     *
     * @param currency the base currency
     * @param targetCurrency the target currency
     * @return the rates or null if there is no such base or target currency
     */
    public Rates getRates(String currency, String targetCurrency) {
        final Currency currencyObject = currencies.get(currency);
        if (currencyObject != null) {
            return currencyObject.getRates(targetCurrency);
        }
        return null;
    }

    /**
     * This is used to apply topic stream updates to the local map and notify
     * listener of changes.
     */
    private void applyUpdate(
        String currency,
        String targetCurrency,
        RecordV2 oldValue,
        RecordV2 newValue) {

        Currency currencyObject = currencies.get(currency);
        if (currencyObject == null) {
            currencyObject = new Currency();
            currencies.put(currency, currencyObject);
        }

        if (schema == null) {
            updateWithoutSchema(
                currency,
                targetCurrency,
                oldValue,
                newValue,
                currencyObject);
        }
        else {
            updateWithSchema(
                currency,
                targetCurrency,
                oldValue,
                newValue,
                currencyObject);
        }
    }

    private void updateWithSchema(
        String currency,
        String targetCurrency,
        RecordV2 oldValue,
        RecordV2 newValue,
        Currency currencyObject) {

        // A data model is generated using the schema allowing direct access to
        // the fields within it
        final RecordModel model = newValue.asModel(schema);
        final String bid = model.get("Bid");
        final String ask = model.get("Ask");

        currencyObject.setRate(targetCurrency, bid, ask);

        if (oldValue == null) {
            listener.onNewRate(currency, targetCurrency, bid, ask);
        }
        else {
            // Generate a structural delta to determine what has changed
            final RecordV2Delta delta = newValue.diff(oldValue);
            for (Change change : delta.changes(schema)) {
                final String fieldName = change.fieldName();
                listener.onRateChange(
                    currency,
                    targetCurrency,
                    fieldName,
                    model.get(fieldName));
            }
        }
    }

    private void updateWithoutSchema(
        String currency,
        String targetCurrency,
        RecordV2 oldValue,
        RecordV2 newValue,
        Currency currencyObject) {

        // All of the fields in the value are obtained.
        final List<String> fields = newValue.asFields();
        final String bid = fields.get(0);
        final String ask = fields.get(1);

        currencyObject.setRate(targetCurrency, bid, ask);

        if (oldValue == null) {
            listener.onNewRate(currency, targetCurrency, bid, ask);
        }
        else {
            // Fields in the old value are obtained to determine what has
            // changed
            final List<String> oldfields = oldValue.asFields();
            final String oldBid = oldfields.get(0);
            final String oldAsk = oldfields.get(1);
            if (!bid.equals(oldBid)) {
                listener.onRateChange(currency, targetCurrency, "Bid", bid);
            }
            if (!ask.equals(oldAsk)) {
                listener.onRateChange(currency, targetCurrency, "Ask", ask);
            }
        }
    }

    private void removeCurrency(String currency) {
        final Currency oldCurrency = currencies.remove(currency);
        for (String targetCurrency : oldCurrency.rates.keySet()) {
            listener.onRateRemoved(currency, targetCurrency);
        }
    }

    private void removeRate(
        String currency,
        String targetCurrency) {

        final Currency currencyObject = currencies.get(currency);
        if (currencyObject != null) {
            if (currencyObject.rates.remove(targetCurrency) != null) {
                listener.onRateRemoved(currency, targetCurrency);
            }
        }
    }

    /**
     * Close session.
     */
    public void close() {
        currencies.clear();
        session.close();
    }

    /**
     * Encapsulates a base currency and all of its known rates.
     */
    private static final class Currency {

        private final Map<String, Rates> rates = new HashMap<>();

        private Rates getRates(String currency) {
            return rates.get(currency);
        }

        private void setRate(String currency, String bid, String ask) {
            rates.put(currency, new Rates(bid, ask));
        }

    }

    /**
     * Encapsulates the rates for a particular base/target currency pair.
     */
    public static final class Rates {

        private final String bidRate;
        private final String askRate;

        /**
         * Constructor.
         *
         * @param bid the bid rate or ""
         * @param ask the ask rate or ""
         */
        private Rates(String bid, String ask) {
            bidRate = bid;
            askRate = ask;
        }

        /**
         * Returns the bid rate.
         *
         * @return bid rate or "" if not available
         */
        public String getBidRate() {
            return bidRate;
        }

        /**
         * Returns the ask rate.
         *
         * @return ask rate or "" if not available
         */
        public String getAskRate() {
            return askRate;
        }

    }

    /**
     * A listener for Rates updates.
     */
    public interface RatesListener {

        /**
         * Notification of a new rate or rate update.
         *
         * @param currency the base currency
         * @param targetCurrency the target currency
         * @param bid rate
         * @param ask rate
         */
        void onNewRate(String currency, String targetCurrency, String bid,
            String ask);

        /**
         * Notification of a change to the bid or ask value for a rate.
         *
         * @param currency the base currency
         * @param targetCurrency the target currency
         * @param bidOrAsk "Bid" or "Ask"
         * @param rate the new rate
         */
        void onRateChange(String currency, String targetCurrency,
            String bidOrAsk, String rate);

        /**
         * Notification of a rate being removed.
         *
         * @param currency the base currency
         * @param targetCurrency the target currency
         */
        void onRateRemoved(String currency, String targetCurrency);
    }

    private final class RatesValueStream
        extends ValueStream.Default<RecordV2> {

        @Override
        public void onSubscription(String topicPath, TopicSpecification specification) {
            final boolean isRatesTopic = Diffusion.topicSelectors().parse("?FX/.*/.*").selects(topicPath);
            // Only retrieve a schema when subscribing to a rates topic
            if (isRatesTopic) {
                final String schemaString = specification.getProperties().get(TopicSpecification.SCHEMA);
                // If a schema is provided on subscription, retrieve it and set it once
                // All schemas are identical for rates topics.
                if (schemaString != null && schema == null) {
                    try {
                        schema = Diffusion.dataTypes().recordV2().parseSchema(schemaString);
                    }
                    catch (SchemaParseException e) {
                        LOG.error("Unable to parse recordV2 schema", e);
                    }
                }
            }
        }

        @Override
        public void onValue(String topicPath, TopicSpecification specification,
            RecordV2 oldValue, RecordV2 newValue) {
            final String[] topicElements = elements(topicPath);
            // It is only a rate update if topic has 2 elements below root path
            if (topicElements.length == 2) {
                applyUpdate(
                    topicElements[0], // The base currency
                    topicElements[1], // The target currency
                    oldValue,
                    newValue);
            }
        }

        @Override
        public void onUnsubscription(String topicPath,
            TopicSpecification specification, UnsubscribeReason reason) {
            final String[] topicElements = elements(topicPath);
            if (topicElements.length == 2) {
                removeRate(topicElements[0], topicElements[1]);
            }
            else if (topicElements.length == 1) {
                removeCurrency(topicElements[0]);
            }
        }

        private String[] elements(String topicPath) {
            final String subPath =
                topicPath.replaceFirst("^" + ROOT_TOPIC + "/", "");
            return subPath.split("/");
        }
    }
}
C
/**
 * Copyright © 2026 DiffusionData Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This example is written in C99. Please use an appropriate C99 capable compiler
 */

#include <stdio.h>
#include <stdlib.h>

#ifndef WIN32
    #include <unistd.h>
#else
    #define sleep(x) Sleep(1000 * x)
#endif

#include "diffusion.h"

static int on_subscription(
    const char *const topic_path,
    const TOPIC_SPECIFICATION_T *specification,
    void *context)
{
    printf("Subscribed to topic: %s\n", topic_path);
    return HANDLER_SUCCESS;
}

static int on_unsubscription(
    const char *const topic_path,
    const TOPIC_SPECIFICATION_T *specification,
    NOTIFY_UNSUBSCRIPTION_REASON_T reason,
    void *context)
{
    printf("Unsubscribed from topic: %s\n", topic_path);
    return HANDLER_SUCCESS;
}

// this example can be run with or without a schema; when a schema is
// supplied as context, values are read using key-based field lookups,
// otherwise the raw fields are read positionally
static int on_value(
    const char *const topic_path,
    const TOPIC_SPECIFICATION_T *specification,
    DIFFUSION_DATATYPE datatype,
    const DIFFUSION_VALUE_T *old_value,
    const DIFFUSION_VALUE_T *new_value,
    void *context)
{
    DIFFUSION_RECORDV2_SCHEMA_T *schema = (DIFFUSION_RECORDV2_SCHEMA_T *) context;

    if (schema != NULL) {
        // a schema allows fields to be read using key-based lookups
        DIFFUSION_RECORDV2_RECORD_MODEL_T *model = NULL;
        diffusion_recordv2_as_model(new_value, schema, &model, NULL);

        char *my_string = NULL;
        char *my_int = NULL;
        char *my_double = NULL;
        diffusion_recordv2_record_model_get_field_value_with_key(model, "myString", &my_string, NULL);
        diffusion_recordv2_record_model_get_field_value_with_key(model, "myInt", &my_int, NULL);
        diffusion_recordv2_record_model_get_field_value_with_key(model, "myDouble", &my_double, NULL);

        printf("myString: %s, myInt: %s, myDouble: %s\n", my_string, my_int, my_double);

        free(my_string);
        free(my_int);
        free(my_double);
        diffusion_recordv2_record_model_free(model);
    }
    else {
        // without a schema, fields can still be read positionally
        LIST_T *fields = NULL;
        diffusion_recordv2_as_fields(new_value, &fields, NULL);

        for (int i = 0; i < list_get_size(fields); i++) {
            printf("Field %d: %s\n", i, (char *) list_get_data_indexed(fields, i));
        }

        list_free(fields, free);
    }

    return HANDLER_SUCCESS;
}

void example(
    const char *url,
    const char *principal,
    CREDENTIALS_T *credentials,
    DIFFUSION_RECORDV2_SCHEMA_T *schema)
{
    const char *topic_path = "my/topic/path";

    SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, NULL);

    VALUE_STREAM_T value_stream = {
        .datatype = DATATYPE_RECORDV2,
        .on_subscription = on_subscription,
        .on_unsubscription = on_unsubscription,
        .on_value = on_value,
        .context = schema};

    add_stream(session, topic_path, &value_stream);

    SUBSCRIPTION_PARAMS_T params = {.topic_selector = topic_path};
    subscribe(session, params);

    // Sleep to receive updates
    sleep(5);

    session_close(session, NULL);
    session_free(session);
}

int main(
    int argc,
    char **argv)
{
    const char *url = "ws://localhost:8080";
    const char *principal = "control";
    const char *password = "password";
    CREDENTIALS_T *credentials = credentials_create_password(password);

    // the schema must match the one used when the topic was created; pass
    // NULL here to read the topic's fields without a schema
    DIFFUSION_RECORDV2_SCHEMA_BUILDER_T *builder = diffusion_recordv2_schema_builder_init();
    diffusion_recordv2_schema_builder_record(builder, "Record", NULL);
    diffusion_recordv2_schema_builder_string(builder, "myString", NULL);
    diffusion_recordv2_schema_builder_integer(builder, "myInt", NULL);
    diffusion_recordv2_schema_builder_decimal(builder, "myDouble", 3, NULL);
    DIFFUSION_RECORDV2_SCHEMA_T *schema = diffusion_recordv2_schema_builder_build(builder, NULL);

    example(url, principal, credentials, schema);

    diffusion_recordv2_schema_builder_free(builder);
    diffusion_recordv2_schema_free(schema);
    credentials_free(credentials);
    return EXIT_SUCCESS;
}
Apple
//  Copyright (C) 2026 DiffusionData Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

import Foundation
import Diffusion

class RecordV2Subscribing {

    func subscribeToRecordV2Topic(session: PTDiffusionSession) {
        let valueStream = PTDiffusionRecordV2.valueStream(with: RecordStream())

        do {
            try session.topics.add(valueStream, withSelectorExpression: "my/topic/path")
        }
        catch {
            print("Error while adding stream with selector expression: \(error.localizedDescription)")
        }

        session.topics.subscribe(withTopicSelectorExpression: "my/topic/path") { (error) in
            if let error = error {
                print("An error has occurred while subscribing: \(error.localizedDescription)")
            }
        }
    }

    class RecordStream: NSObject, PTDiffusionRecordV2ValueStreamDelegate {
        var schema: PTDiffusionRecordV2Schema?

        func diffusionStream(_ stream: PTDiffusionStream,
                             didSubscribeToTopicPath topicPath: String,
                             specification: PTDiffusionTopicSpecification) {
            print("Client subscribed to topic '\(topicPath)'.")

            // retrieve the schema from the topic properties when subscribing
            if let schemaString = specification.properties[PTDiffusionTopicSpecification.schemaPropertyKey()],
               let schemaData = schemaString.data(using: .utf8) {
                schema = try? PTDiffusionRecordV2Schema(jsonData: schemaData)
            }
        }

        func diffusionStream(_ stream: PTDiffusionValueStream,
                             didUpdateTopicPath topicPath: String,
                             specification: PTDiffusionTopicSpecification,
                             oldRecord: PTDiffusionRecordV2?,
                             newRecord: PTDiffusionRecordV2) {
            guard let schema = self.schema else {
                return
            }

            // use the schema to produce a model that allows key-based lookup of fields
            let model = try! newRecord.model(with: schema)
            let myString = try! model.fieldValue(forKey: "myString")
            let myInt = try! model.fieldValue(forKey: "myInt")
            let myDouble = try! model.fieldValue(forKey: "myDouble")
            print("myString: \(myString), myInt: \(myInt), myDouble: \(myDouble).")

            if let oldRecord = oldRecord {
                // generate a structural delta to determine what has changed
                let delta = newRecord.diff(fromOriginalRecord: oldRecord)
                for change in try! delta.changes(with: schema) {
                    let fieldName = change.fieldName
                    print("Field '\(fieldName)' changed to '\(try! model.fieldValue(forKey: fieldName))'.")
                }
            }
        }

        func diffusionStream(_ stream: PTDiffusionStream,
                             didUnsubscribeFromTopicPath topicPath: String,
                             specification: PTDiffusionTopicSpecification,
                             reason: PTDiffusionTopicUnsubscriptionReason) {
            print("Client unsubscribed from topic '\(topicPath)'.")
        }

        func diffusionStream(_ stream: PTDiffusionStream,
                             didFailWithError error: Error) {
            print("Value stream failed with error: \(error.localizedDescription)")
        }

        func diffusionDidClose(_ stream: PTDiffusionStream) {
            print("Value stream is now closed.")
        }
    }
}