Just a second...

Update recordV2 topics

The following example demonstrates how to create and update recordV2 topics, including the use of a schema.

This example demonstrates a Java™ control client updating recordV2 topics.

JavaScript
import * as diffusion from 'diffusion';

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

    // define a schema consisting of a single record with three fields,
    // each of a different data type
    const schema = diffusion.datatypes.recordv2().schemaBuilder()
        .record('Record').string('myString').integer('myInt').decimal('myDouble', 3)
        .build();

    // create a topic specification with our schema as a property
    const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.RECORD_V2, {
        SCHEMA : schema.asJSON()
    });

    await session.topics.add('my/topic/path', specification);

    // create a value for our topic using the schema
    const model = schema.createMutableModel();
    model.set('myString', 'Hello World');
    model.set('myInt', '5');
    model.set('myDouble', '3.141');

    // update the topic with our value
    await session.topicUpdate.set('my/topic/path', diffusion.datatypes.recordv2(), model.asValue());
}
.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.Factories;
using PushTechnology.ClientInterface.Client.Topics;
using PushTechnology.ClientInterface.Client.Topics.Details;

namespace PushTechnology.ClientInterface.Example {
    /// <summary>
    /// Client creating and updating a RecordV2 topic, using a schema.
    /// </summary>
    public sealed class RecordV2Updating {
        public async Task RecordV2UpdatingExample(string serverUrl)
        {
            var session = Diffusion.Sessions.Open(serverUrl);

            // define a schema consisting of a single record with three fields,
            // each of a different data type
            var schema = Diffusion.DataTypes.RecordV2.CreateSchemaBuilder()
                .Record("Record")
                .String("myString").Integer("myInt").Decimal("myDouble", 3)
                .Build();

            // create a topic specification with our schema as a property
            var specification = new TopicSpecification(TopicType.RECORD_V2)
                .WithProperty(TopicSpecificationProperty.SCHEMA, schema.ToJSONString());

            // add the topic
            await session.TopicControl.AddTopicAsync("my/topic/path", specification);

            // create a value for our topic using the schema
            var model = schema.CreateMutableModel();
            model.Set("myString", "Hello World");
            model.Set("myInt", "5");
            model.Set("myDouble", "3.141");

            // update the topic with our value
            await session.TopicUpdate.SetAsync("my/topic/path", model.AsValue());

            session.Close();
        }
    }
}
Java and Android
/*******************************************************************************
 * Copyright (C) 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 com.pushtechnology.diffusion.client.Diffusion;
import com.pushtechnology.diffusion.client.callbacks.ErrorReason;
import com.pushtechnology.diffusion.client.features.TopicUpdate;
import com.pushtechnology.diffusion.client.features.Topics;
import com.pushtechnology.diffusion.client.features.control.topics.TopicControl;
import com.pushtechnology.diffusion.client.session.Session;
import com.pushtechnology.diffusion.client.topics.details.TopicSpecification;
import com.pushtechnology.diffusion.client.topics.details.TopicType;
import com.pushtechnology.diffusion.datatype.recordv2.RecordV2;
import com.pushtechnology.diffusion.datatype.recordv2.schema.Schema;
import com.pushtechnology.diffusion.datatype.recordv2.schema.SchemaBuilder;

/**
 * Client creating and updating RecordV2 topics.
 *
 * @author DiffusionData Limited
 */
public final class RecordV2Updating {

    public static void main(String[] args) {

        final Session session = Diffusion.sessions()
            .principal("admin")
            .password("password")
            .open("ws://localhost:8080");

        final TopicControl topicControl = session.feature(TopicControl.class);
        final SchemaBuilder builder = Diffusion.dataTypes()
            .recordV2().schemaBuilder();

        // define a schema consisting of a single record with three fields each
        // of a different data type.
        final Schema schema = builder
            .record("Record")
            .string("myString").integer("myInt").decimal("myDouble", 3)
            .build();

        // create a topic specification with our schema as a property
        final TopicSpecification specification = Diffusion
            .newTopicSpecification(TopicType.RECORD_V2)
            .withProperty(TopicSpecification.SCHEMA, schema.asJSONString());

        // add the topic
        topicControl.addTopic("my/topic/path", specification);

        // add a value stream and subscribe to receive updates
        session.feature(Topics.class).addStream(
            "?my/topic/path",
            RecordV2.class,
            new MyValueStream());
        session.feature(Topics.class).subscribe("?my/topic/path");

        // create a value for our topic
        final RecordV2 value = schema.createMutableModel()
            .set("myString", "Hello World")
            .set("myInt", "5")
            .set("myDouble", "3.141")
            .asValue();

        //update the topic with our value
        session.feature(TopicUpdate.class).set(
            "my/topic/path",
            RecordV2.class,
            value
        ).join();
    }

    private static final class MyValueStream implements Topics.ValueStream<RecordV2> {
        @Override
        public void onValue(String topicPath,
            TopicSpecification specification, RecordV2 oldValue,
            RecordV2 newValue) {
            System.out.printf("new value: %s\n", newValue.asFields());
        }

        @Override
        public void onSubscription(String topicPath,
            TopicSpecification specification) { }

        @Override
        public void onUnsubscription(String topicPath,
            TopicSpecification specification, Topics.UnsubscribeReason reason) { }

        @Override
        public void onClose() { }

        @Override
        public void onError(ErrorReason errorReason) { }
    }
}
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>

#include "diffusion.h"

static int on_topic_added(
    SESSION_T *session,
    TOPIC_ADD_RESULT_CODE result_code,
    void *context)
{
    printf("Topic added.\n");
    return HANDLER_SUCCESS;
}

static int on_topic_add_failed(
    SESSION_T *session,
    TOPIC_ADD_FAIL_RESULT_CODE result_code,
    const DIFFUSION_ERROR_T *error,
    void *context)
{
    fprintf(stderr, "Failed to add topic: %s\n", error->message);
    return HANDLER_SUCCESS;
}

static int on_topic_update(
    void *context)
{
    printf("Topic update success.\n");
    return HANDLER_SUCCESS;
}

static int on_error(
    SESSION_T *session,
    const DIFFUSION_ERROR_T *error)
{
    printf("Topic update error: %s\n", error->message);
    return HANDLER_SUCCESS;
}

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

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

    // define a schema consisting of a single record with three fields,
    // each of a different data type
    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);
    char *schema_json = diffusion_recordv2_schema_as_json_string(schema);

    // create a topic specification with our schema as a property
    HASH_T *properties = hash_new(1);
    hash_add(properties, DIFFUSION_SCHEMA, schema_json);
    TOPIC_SPECIFICATION_T *specification = topic_specification_init_with_properties(TOPIC_TYPE_RECORDV2, properties);

    ADD_TOPIC_CALLBACK_T add_topic_callback = {
        .on_topic_added_with_specification = on_topic_added,
        .on_topic_add_failed_with_specification = on_topic_add_failed};
    add_topic_from_specification(session, topic_path, specification, add_topic_callback);

    // create a value for our topic, matching the field order of the schema
    DIFFUSION_RECORDV2_BUILDER_T *value_builder = diffusion_recordv2_builder_init();
    char *fields[] = {"Hello World", "5", "3.141"};
    diffusion_recordv2_builder_add_record(value_builder, fields);
    void *record_bytes = diffusion_recordv2_builder_build(value_builder);

    BUF_T *buf = buf_create();
    write_diffusion_recordv2_value(record_bytes, buf);

    // update the topic with our value
    DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T update_params = {
        .topic_path = topic_path,
        .datatype = DATATYPE_RECORDV2,
        .update = buf,
        .on_topic_update = on_topic_update,
        .on_error = on_error};
    diffusion_topic_update_set(session, update_params);

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

    diffusion_recordv2_builder_free(value_builder);
    diffusion_recordv2_schema_builder_free(builder);
    diffusion_recordv2_schema_free(schema);
    buf_free(buf);
    free(record_bytes);
    hash_free(properties, NULL, free);
    topic_specification_free(specification);
}

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);

    example(url, principal, credentials);

    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 RecordV2Updating {

    func updateRecordV2Topic(session: PTDiffusionSession) {
        // define a schema consisting of a single record with three fields,
        // each of a different data type
        let schema = PTDiffusionRecordV2SchemaBuilder()
            .addRecord(withName: "Record")
            .addString(withName: "myString")
            .addInteger(withName: "myInt")
            .addDecimal(withName: "myDouble", scale: 3)
            .build()

        // create a topic specification with our schema as a property
        let schemaString = String(data: schema.jsonData(), encoding: .utf8)!
        let specification = PTDiffusionTopicSpecification(
            type: PTDiffusionTopicType.recordV2,
            properties: [PTDiffusionTopicSpecification.schemaPropertyKey(): schemaString])

        // add the topic
        session.topicControl.addTopic(withPath: "my/topic/path",
                                      specification: specification) { (result, error) in
            if let error = error {
                print("An error has occurred while adding the topic: \(error.localizedDescription)")
                return
            }

            // create a value for our topic using the schema
            let model = schema.createMutableModel()
            try! model.setFieldValue("Hello World", forKey: "myString")
            try! model.setFieldValue("5", forKey: "myInt")
            try! model.setFieldValue("3.141", forKey: "myDouble")
            let value = try! model.value()

            // update the topic with our value
            session.topicUpdate.setWithPath("my/topic/path",
                                            toRecordValue: value) { (error) in
                if let error = error {
                    print("An error has occurred while updating the topic: \(error.localizedDescription)")
                }
            }
        }
    }
}