The Art of Data Synchronization in HarmonyOS Next: Distributed Objects and Cross-Device Invocation

xun_wang_6384a403f9817c2

SameX

Posted on November 16, 2024

The Art of Data Synchronization in HarmonyOS Next: Distributed Objects and Cross-Device Invocation

This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now), and is summarized based on actual development practices. It mainly serves as a carrier for technical sharing and communication. Mistakes and omissions are inevitable. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.

Overview

In today's intelligent device ecosystem, users expect to seamlessly continue their work and entertainment activities on different devices. Huawei HarmonyOS Next, through its distributed data object technology, provides developers with a powerful solution to achieve multi-terminal data collaboration. This article will conduct an in-depth exploration of how to use distributed data objects to implement cross-device data synchronization invocation and session management, as well as how to apply these technologies in actual projects.

Cross-Device Data Synchronization Invocation

Distributed data objects are an advanced technology in HarmonyOS Next that enables data to be synchronized in real-time across multiple devices, thereby achieving true multi-terminal collaboration. The following are the detailed steps and examples for implementing cross-device data synchronization invocation:

1. Create a Distributed Data Object

Before starting, we need to create a distributed data object, which is the foundation for cross-device data synchronization.

import distributedObject from '@ohos.data.distributedObject';
// Define the configuration of the distributed data object
const config = {
    bundleName: 'com.example.app',
    abilityName: 'DistributedAbility',
    objectId: 'myObjectId'
};
// Create the distributed data object
const distributedObj = distributedObject.createDistributedObject(config);
Enter fullscreen mode Exit fullscreen mode
2. Synchronize Data to Other Devices

Once the distributed data object has been created, we can start synchronizing data. The following is an example of how to update data and synchronize it to other devices:

// Update the data of the distributed data object
async function updateData(key: string, value: any) {
    try {
        await distributedObj.set(key, value);
        console.log(`Data for key "${key}" updated and synchronized across devices.`);
    } catch (error) {
        console.error('Failed to update data:', error);
    }
}
// Example: Synchronize temperature data
updateData('temperature', 22);
Enter fullscreen mode Exit fullscreen mode
3. Listen for Data Changes

To achieve real-time data collaboration, we can listen for data change events of the distributed data object.

// Listen for data changes
distributedObj.on('dataChange', (changes) => {
    changes.forEach(change => {
        console.log(`Data changed for key "${change.key}": ${change.value}`);
    });
});
Enter fullscreen mode Exit fullscreen mode

Session Management of Distributed Data Objects

Session management is the key to ensuring that distributed data objects interact correctly in a multi-device environment. The following are the detailed steps and examples for managing distributed data object sessions:

1. Session Creation and Listening

In multi-device collaboration, session management is of great importance. The following is an example of how to create a session and listen for its state:

// Create a session
const session = distributedObj.createSession();
// Listen for session state changes
session.on('sessionStateChange', (state) => {
    console.log(`Session state changed to: ${state}`);
});
Enter fullscreen mode Exit fullscreen mode
2. Session Closure

When the session is no longer needed, it should be closed properly to release resources.

// Close the session
async function closeSession() {
    try {
        await session.close();
        console.log('Session closed successfully.');
    } catch (error) {
        console.error('Failed to close session:', error);
    }
}
Enter fullscreen mode Exit fullscreen mode

Complete Example: Achieving Data Collaboration between Multiple Devices

The following is a complete example showing how to achieve data collaboration between multiple devices in a project:

// Import the distributed data object module
import distributedObject from '@ohos.data.distributedObject';
// Define the configuration of the distributed data object
const config = {
    bundleName: 'com.example.app',
    abilityName: 'DistributedAbility',
    objectId: 'myObjectId'
};
// Create the distributed data object
const distributedObj = distributedObject.createDistributedObject(config);
// Update the data of the distributed data object
async function updateData(key: string, value: any) {
    try {
        await distributedObj.set(key, value);
        console.log(`Data for key "${key}" updated and synchronized across devices.`);
    } catch (error) {
    }
}
// Create a session and listen for state changes
const session = distributedObj.createSession();
session.on('sessionStateChange', (state) => {
    console.log(`Session state changed to: ${state}`);
});
// Listen for data changes
distributedObj.on('dataChange', (changes) => {
    changes.forEach(change => {
        console.log(`Data changed for key "${change.key}": ${change.value}$$);
    });
});
// Example: Synchronize temperature data
updateData('temperature', 22);
// Close the session at the appropriate time
closeSession();
Enter fullscreen mode Exit fullscreen mode

In the above example, we first created a distributed data object and defined the method for updating data. Then, we created a session and listened for the state change of the session. We also set up a listener for data change events so that we could be notified when the data was updated.

💖 💪 🙅 🚩
xun_wang_6384a403f9817c2
SameX

Posted on November 16, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related