未验证 提交 714ccdef 编写于 作者: O openharmony_ci 提交者: Gitee

!23805 [翻译完成】#I7W570

Merge pull request !23805 from Annie_wang/PR23009
......@@ -30,23 +30,23 @@ The preference persistent file of an application is stored in the application sa
The following table lists the APIs used for persisting user preference data. For more information about the APIs, see [User Preferences](../reference/apis/js-apis-data-preferences.md).
| API | Description |
|--------------------------------------------------------------------------------------------------|------------------------------------------------------------|
| getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void | Obtain a **Preferences** instance. |
| putSync(key: string, value: ValueType): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data. An asynchronous API is also provided. |
| hasSync(key: string): void | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty. An asynchronous API is also provided. |
| getSync(key: string, defValue: ValueType): void | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned. An asynchronous API is also provided. |
| deleteSync(key: string): void | Deletes the KV pair with the given key from the **Preferences** instance. An asynchronous API is also provided. |
| flush(callback: AsyncCallback<void>): void | Flushes the data of this **Preferences** instance to a file for data persistence. |
| on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes of the specified key. When the value of the specified key is changed and saved by **flush()**, a callback will be invoked to return the new data. |
| off(type: 'change', callback?: Callback<{ key : string }>): void | Unsubscribes from data changes. |
| deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file.|
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void | Obtains a **Preferences** instance. |
| putSync(key: string, value: ValueType): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data. An asynchronous API is also provided. |
| hasSync(key: string): void | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty. An asynchronous API is also provided. |
| getSync(key: string, defValue: ValueType): void | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned. An asynchronous API is also provided. |
| deleteSync(key: string): void | Deletes the KV pair with the given key from the **Preferences** instance. An asynchronous API is also provided. |
| flush(callback: AsyncCallback<void>): void | Flushes the data of this **Preferences** instance to a file for data persistence. |
| on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes of the specified key. When the value of the specified key is changed and saved by **flush()**, a callback will be invoked to return the new data. |
| off(type: 'change', callback?: Callback<{ key : string }>): void | Unsubscribes from data changes. |
| deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file. |
## How to Develop
1. Import the **@ohos.data.preferences** module.
```js
import dataPreferences from '@ohos.data.preferences';
```
......@@ -55,14 +55,16 @@ The following table lists the APIs used for persisting user preference data. For
Stage model:
```js
import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
import window from '@ohos.window';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
onWindowStageCreate(windowStage: window.WindowStage) {
try {
dataPreferences.getPreferences(this.context, 'mystore', (err, preferences) => {
dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => {
if (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
return;
......@@ -79,15 +81,16 @@ The following table lists the APIs used for persisting user preference data. For
FA model:
```js
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base';
// Obtain the context.
let context = featureAbility.getContext();
try {
dataPreferences.getPreferences(context, 'mystore', (err, preferences) => {
dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => {
if (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
return;
......@@ -102,7 +105,7 @@ The following table lists the APIs used for persisting user preference data. For
3. Write data.
Use **putSync()** to write data to the cached **Preferences** instance. After data is written, you can use **flush()** to persist the **Preferences** instance data to a file if necessary.
Use **putSync()** to save data to the cached **Preferences** instance. After data is written, you can use **flush()** to persist the **Preferences** instance data to a file if necessary.
> **NOTE**
>
......@@ -110,7 +113,7 @@ The following table lists the APIs used for persisting user preference data. For
Example:
```js
try {
if (preferences.hasSync('startup')) {
......@@ -142,7 +145,7 @@ The following table lists the APIs used for persisting user preference data. For
Use **deleteSync()** to delete a KV pair.<br>Example:
```js
try {
preferences.deleteSync('startup');
......@@ -157,7 +160,7 @@ The following table lists the APIs used for persisting user preference data. For
```js
try {
preferences.flush((err) => {
preferences.flush((err: BusinessError) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return;
......@@ -174,18 +177,20 @@ The following table lists the APIs used for persisting user preference data. For
Specify an observer as the callback to return the data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. Example:
```js
let observer = function (key) {
console.info('The key' + key + 'changed.');
interface observer {
key: string
}
preferences.on('change', observer);
preferences.on('change', (key: observer) => {
console.info('The key' + key + 'changed.');
});
// The data is changed from 'auto' to 'manual'.
preferences.put('startup', 'manual', (err) => {
preferences.put('startup', 'manual', (err: BusinessError) => {
if (err) {
console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`);
return;
}
console.info("Succeeded in putting the value of 'startup'.");
preferences.flush((err) => {
preferences.flush((err: BusinessError) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return;
......@@ -207,10 +212,10 @@ The following table lists the APIs used for persisting user preference data. For
Example:
```js
try {
dataPreferences.deletePreferences(this.context, 'mystore', (err, val) => {
dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => {
if (err) {
console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
return;
......
......@@ -3,26 +3,30 @@
## When to Use
To implement traditional data synchronization between devices, you need to design the message processing logic, including setting up a communication link, sending, receiving, and processing messages, retry mechanism upon errors, and resolving data conflicts. The workload is heavy. In addition, the debugging complexity increases with the number of devices.
The traditional implementation of data synchronization between devices involves heavy workload. You need to design the message processing logic for setting up a communication link, sending, receiving, and processing messages, and resolving data conflicts, as well as retry mechanism upon errors. In addition, the debugging complexity increases with the number of devices.
The device status, message sending progress, and data transmitted are variables. If these variables support global access, they can be accessed as local variables on difference devices. This simplifies data synchronization between multiple devices.
The device status, message sending progress, and data transmitted are variables. If these variables support global access, they can be accessed as local variables by difference devices. This simplifies data synchronization across devices.
The distributed data object (**DataObject**) implements global access to variables. **DataObject** provides basic data object management capabilities and distributed capabilities. You can use the APIs to create, query, delete, and modify in-memory objects and subscribe to event notifications. OpenHarmony also provides easy-to-use JS APIs for distributed application scenarios to easily implement cross-device data collaboration for the same application. In addition, object status and data changes on different devices can be observed. This feature implements data object collaboration for the same application between multiple devices that form a Super Device. **DataObject** greatly reduces the development workloads compared with the traditional mode.
The distributed data object (**distributedDataObject**) module implements global access to variables. It provides basic data object management capabilities, including creating, querying, deleting, and modifying in-memory objects and subscribing to data or status changes. It also provides distributed capabilities. OpenHarmony provides easy-to-use JS APIs for distributed application scenarios. With these APIs, you can easily implement data collaboration for an application across devices and listening for status and data changes between devices. The **distributedDataObject** module implements data object collaboration for the same application across multiple devices that form a Super Device. It greatly reduces the development workloads compared with the traditional implementation.
## Basic Concepts
- Distributed in-memory database<br>
The distributed in-memory database caches data in the memory so that applications can quickly access data without persisting data. If the database is closed, the data is not retained.
- Distributed in-memory database
The distributed in-memory database caches data in the memory so that applications can quickly access data without persisting data. If the database is closed, the data is not retained.
- Distributed data object
A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading data from and writing data to a distributed data object are mapped to the **get()** and **put()** operations in the corresponding database, respectively.
The distributed data object can be in the following states in its lifecycle:
A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading and writing a distributed data object are mapped to the **get** and **put** operations in the corresponding database, respectively.
- **Uninitialized**: The distributed data object is not instantiated or has been destroyed.
- **Local**: The data table is created, but the data cannot be synchronized.
- **Distributed**: The data table is created, and there are at least two online devices with the same session ID. In this case, data can be synchronized across devices. If a device is offline or the session ID is empty, the distributed data object changes to the local state.
The distributed data object has the following states in its lifecycle:
- **Uninitialized**: The distributed data object is not instantiated or is destroyed.
- **Local**: A data table is created, but the data cannot be synchronized.
- **Distributed**: A data table is created, and data can be synchronized (there are at least two online devices with the same session ID). If a device is offline or the session ID is empty, the distributed data object changes to the local state.
## Working Principles
......@@ -31,201 +35,221 @@ The distributed data object (**DataObject**) implements global access to variabl
![distributedObject](figures/distributedObject.jpg)
The distributed data objects are encapsulated into JS objects in distributed in-memory databases. This allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization.
The distributed data objects are encapsulated JS objects in distributed in-memory databases, and can be operated in the same way as local variables. The system automatically implements data synchronization across devices.
### JS Object Storage and Encapsulation Mechanism
### Encapsulation and Storage of JS Objects
- An in-memory database is created for each distributed data object instance and identified by a session ID (**SessionId**). The in-memory databases created for different applications are isolated from each other.
- When a distributed data object is instantiated, all properties of the object are traversed recursively. **Object.defineProperty** is used to define the **set()** and **get()** methods of all properties. The **set()** and **get()** methods correspond to the **put** and **get** operations of a record in the database, respectively. **Key** specifies the property name, and **Value** specifies the property value.
- When a distributed data object is instantiated, all properties of the object are traversed recursively. **Object.defineProperty** is used to define the **set()** and **get()** methods for all properties. The **set()** and **get()** methods correspond to the **put** and **get** operations of a record in the database, respectively. **Key** specifies the property name, and **Value** specifies the property value.
- When a distributed data object is read or written, the **set()** and **get()** methods are automatically called to perform the related operations to the database.
- When a distributed data object is read or written, the **get()** or **set()** method is automatically called to perform the related operation on data in the database.
**Table 1** Correspondence between a distributed data object and a distributed database
| Distributed Data Object Instance| Object Instance| Property Name| Property Value|
| Distributed Data Object Instance| Object Instance| Property Name| Property Value|
| -------- | -------- | -------- | -------- |
| Distributed in-memory database| Database identified by **sessionID**| Key of a record in the database| Value of a record in the database|
| Distributed in-memory database| Database identified by **sessionID**| Key of a record in the database| Value of a record in the database|
### Cross-Device Synchronization and Data Change Notification Mechanism
### Cross-Device Synchronization and Data Change Notification
The distributed data object is used to implement data synchronization between objects. You can create a distributed data object and set **sessionID** for the devices on a trusted network. The distributed data objects with the same **sessionID** on different devices can synchronize data with each other.
One of the most important functions of distributed data objects is to implement data synchronization between objects. Distributed data objects are created locally for the devices on a trusted network. If the distributed data objects on different devices are set with the same **sessionID**, data can be synchronized between them.
As shown in the following figure, distributed data object 1 on device A and device B have the same session ID **session1**. The synchronization relationship of session1 is established between the two objects.
As shown in the following figure, distributed data object 1 of device A and distributed data object 1 of device B are set with the same session ID **session1**, and synchronization relationship of session 1 is established between the two objects.
**Figure 2** Object synchronization relationship
**Figure 2** Object synchronization relationship
![distributedObject_sync](figures/distributedObject_sync.jpg)
For each device, only one object can be added to a synchronization relationship. As shown in the preceding figure, distributed data object 2 of device A cannot be added to session 1 because distributed data object 1 of device A has been added to session 1.
For each device, only one distributed data object can be added to a synchronization relationship. As shown in the preceding figure, distributed data object 2 of device A cannot be added to session 1 because distributed data object 1 of device A has been added to session 1.
After the synchronization relationship is established, each session has a copy of shared object data. The distributed data objects added to a session support the following operations:
After the synchronization relationship is established, each session has a copy of shared object data. The distributed data objects added to the same session support the following operations:
- Reading or modifying the data in the session.
(1) Reading or modifying the data in the session.
- Listening for data changes made by other devices.
(2) Listening for data changes made by other devices.
- Listening for status changes, such as the addition and removal of other devices.
(3) Listening for status changes, such as the addition and removal of other devices.
### Minimum Unit to Synchronize
### Minimum Synchronization Unit
Attribute is the minimum unit to synchronize in distributed data objects. For example, object 1 in the following figure has three attributes: name, age, and parents. If one of the attributes is changed, only the changed attribute needs to be synchronized.
Property is the minimum unit to synchronize in distributed data objects. For example, object 1 in the following figure has three properties: name, age, and parents. If one of the properties is changed, only the changed attribute needs to be synchronized.
**Figure 3** Synchronization of distributed data objects
![distributedObject_syncView](figures/distributedObject_syncView.jpg)
### Object Persistence Mechanism
### Persistence of Distributed Data Objects
Distributed data objects run in the process space of applications. When the data of a distributed data object is persisted in the distributed database, the data will not be lost after the application exits.
Distributed data objects run in the process space of applications. After the data of a distributed data object is persisted in the distributed database, the data will not be lost after the application exits.
You need to persist distributed data objects in the following scenarios:
- Enable an application to retrieve the exact same data after it is opened again. In this case, you need to persist the distributed data object (for example, object 1). After the application is opened again, create a distributed data object (for example, object 2) and set the session ID of object 1 for object 2. Then, the application can retrieve the data of object 1.
- Enable an application to retrieve the exact same data after it starts again. In this case, you need to persist the distributed data object (for example, object 1 with session ID 1). After the application starts again, create a distributed data object (for example, object 2) and set the session ID to 1. Then, the application can retrieve the data of object 1.
- Enable an application opened on another device to retrieve the exact same data. In this case, you need to persist the distributed data object (for example, object 1) on device A and synchronize the data to device B. Then, create a distributed data object (for example, object 2) and set the session ID of object 1 for object 2. When the application is opened on device B, it can retrieve the same application data used on device A before the application is closed.
- Enable an application started on another device to retrieve the exact same data. In this case, you need to persist the distributed data object (for example, object 1 with session ID 1) on device A and synchronize the data to device B. Then, create a distributed data object (for example, object 2) and set the session ID to 1. When the application is started on device B, it can retrieve the same application data used on device A before the application is closed.
## Constraints
- Data synchronization can be implemented across devices only for the applications with the same **bundleName**.
- Only the data of the same application can be synchronized across devices, that is, the devices must have the same **bundleName**.
- Data can be synchronized only for the distributed data objects with the same **sessionID** of the same application.
- Data can be synchronized for the distributed data objects with the same session ID.
- Each distributed data object occupies 100 KB to 150 KB of memory. Therefore, you are advised not to create too many distributed data objects.
- The maximum size of a distributed data object is 500 KB.
- It takes about 50 ms from the time when 1 KB of data starts to be modified on a device to the time when another device receives a data change notification.
- If data of 1 KB data is modified on device A, device B can complete data update within 50 ms after receiving a data change notification.
- A maximum of 16 distributed data object instances can be created for an application.
- For optimal performance and user experience, the maximum number of devices for data collaboration is 3.
- For the sake of performance and user experience, the maximum number of devices for data collaboration is 3.
- For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified.
- For the distributed data object of the complex type, only the root property can be modified. The subordinate properties cannot be modified.
- Only JS APIs are supported.
- Currently, only JS APIs are supported.
## Available APIs
The following table lists the APIs for cross-device synchronization of distributed data objects. Most of the interfaces are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
Most of the APIs for cross-device synchronization of distributed data objects are executed asynchronously in callback or promise mode. The following table uses the callback-based APIs as an example. For more information about the APIs, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
| API| Description|
| API| Description|
| -------- | -------- |
| create(context: Context, source: object): DataObject | Creates a distributed data object instance.|
| genSessionId(): string | Generates a session ID for distributed data objects.|
| setSessionId(sessionId: string, callback: AsyncCallback&lt;void&gt;): void | Sets a session ID for data synchronization. Automatic synchronization is performed for devices with the same session ID on a trusted network.|
| setSessionId(callback: AsyncCallback&lt;void&gt;): void | Exits all sessions.|
| on(type: 'change', callback: Callback&lt;{ sessionId: string, fields: Array&lt;string&gt; }&gt;): void | Subscribes to data changes of this distributed data object.|
| on(type: 'status', callback: Callback&lt;{ sessionId: string, networkId: string, status: 'online' \| 'offline' }&gt;): void | Subscribes to status changes of this distributed data object.|
| save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object.|
| revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the save operation of the distributed data object.|
| create(context: Context, source: object): DataObject | Creates a distributed data object instance.|
| genSessionId(): string | Generates a session ID for distributed data objects.|
| setSessionId(sessionId: string, callback: AsyncCallback&lt;void&gt;): void | Sets a session ID for data synchronization. Automatic synchronization is performed for devices with the same session ID on a trusted network.|
| setSessionId(callback: AsyncCallback&lt;void&gt;): void | Exits all sessions.|
| on(type: 'change', callback: Callback&lt;{ sessionId: string, fields: Array&lt;string&gt; }&gt;): void | Subscribes to data changes of this distributed data object.|
| on(type: 'status', callback: Callback&lt;{ sessionId: string, networkId: string, status: 'online' \| 'offline' }&gt;): void | Subscribes to status changes of this distributed data object.|
| save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object.|
| revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the saving of the distributed data object.|
## How to Develop
The following example demonstrates how to implement a distributed data object synchronization.
The following example demonstrates how to implement synchronization of distributed data objects.
1. Import the **@ohos.data.distributedDataObject** module.
```js
import distributedDataObject from '@ohos.data.distributedDataObject';
```
2. Request permissions.
2. Apply for required permissions.
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
1. Apply for the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
3. Creates a distributed data object instance.
3. Create a distributed data object instance.
Stage model:
```js
// Import the module.
import distributedDataObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
import window from '@ohos.window';
interface sourceObject{
name: string,
age: number,
isVis: boolean
parent: { [key: string]: string },
list: { [key: string]: string }[]
}
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types.
let localObject = distributedDataObject.create(this.context, {
onWindowStageCreate(windowStage: window.WindowStage) {
let source: sourceObject = {
name: 'jack',
age: 18,
isVis: false,
parent: { mother: 'jack mom', father: 'jack Dad' },
list: [{ mother: 'jack mom' }, { father: 'jack Dad' }]
});
}
let localObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, source);
}
}
```
FA model:
```js
// Import the module.
import distributedDataObject from '@ohos.data.distributedDataObject';
import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context.
let context = featureAbility.getContext();
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types.
let localObject = distributedDataObject.create(context, {
interface sourceObject{
name: string,
age: number,
isVis: boolean
parent: { [key: string]: string },
list: { [key: string]: string }[]
}
let source: sourceObject = {
name: 'jack',
age: 18,
isVis: false,
parent: { mother: 'jack mom', father: 'jack Dad' },
list: [{ mother: 'jack mom' }, { father: 'jack Dad' }]
});
}
// Create a distributed data object, which has properties of the string, number, boolean, and object types.
let localObject: distributedDataObject.DataObject = distributedDataObject.create(context, source);
```
4. Set the same session ID for the distributed data objects for data synchronization. The data objects in the synchronization network include the local and remote objects.
```js
// Set a session ID, for example, 123456, for device 1.
let sessionId = '123456';
let sessionId: string = '123456';
localObject.setSessionId(sessionId);
// Set the same session ID for device 2.
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types.
let remoteObject = distributedDataObject.create(this.context, {
// Create a distributed data object, which has properties of the string, number, boolean, and object types.
let remoteSource: sourceObject = {
name: undefined,
age: undefined, // undefined indicates that the data comes from the peer end.
isVis: true,
parent: undefined,
list: undefined
});
// After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
}
let remoteObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, remoteSource);
// After learning that the device goes online, the remote object synchronizes data. That is, name is changed to jack and age to 18.
remoteObject.setSessionId(sessionId);
```
5. Observe data changes of a distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return a data change event.
```js
function changeCallback(sessionId, changeData) {
console.info(`change: ${sessionId}`);
if (changeData !== null && changeData !== undefined) {
changeData.forEach(element => {
console.info(`The element ${localObject[element]} changed.`);
});
}
```js
interface ChangeCallback {
sessionId: string,
fields: Array<string>
}
// To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
localObject.on("change", this.changeCallback.bind(this));
localObject.on("change", (changeData:ChangeCallback) => {
console.info("change" + changeData.sessionId);
if (changeData.fields != null && changeData.fields != undefined) {
for (let index: number = 0; index < changeData.fields.length; index++) {
console.info(`The element ${localObject[changeData.fields[index]]} changed.`);
}
}
});
```
6. Modify attributes of the distributed data object. The object attributes support basic data types (number, Boolean, and string) and complex data types (array and nested basic types).
6. Modify properties of the distributed data object. The object properties support basic data types (number, Boolean, and string) and complex data types (array and nested basic types).
```js
localObject.name = 'jack1';
localObject.age = 19;
......@@ -236,9 +260,9 @@ The following example demonstrates how to implement a distributed data object sy
> **NOTE**
>
> For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified.
> For the distributed data object of the complex type, only the root property can be modified. The subordinate properties cannot be modified.
```js
// Supported modification.
localObject.parent = { mother: 'mom', father: 'dad' };
......@@ -246,62 +270,82 @@ The following example demonstrates how to implement a distributed data object sy
localObject.parent.mother = 'mom';
```
7. Access a distributed data object. Obtain the distributed data object attributes, which are the latest data on the network.
7. Access a distributed data object. Obtain the distributed data object properties, which are the latest data on the network.
```js
console.info(`name:${localObject['name']}`);
```
8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered.
8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all data change callbacks of the distributed data object.
```js
// Unregister this.changeCallback.
localObject.off('change', this.changeCallback);
localObject.off('change',(changeData: ChangeCallback) => {
console.info("change" + changeData.sessionId);
if (changeData.fields != null && changeData.fields != undefined) {
for (let index: number = 0; index < changeData.fields.length; index++) {
console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]);
}
}
});
// Unregister all data change callbacks.
localObject.off('change');
```
9. Subscribes to status changes of a distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
9. Subscribe to status changes of a distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
```js
function statusCallback(sessionId, networkId, status) {
// Service processing.
interface onStatusCallback {
sessionId: string,
networkId: string,
status: 'online' | 'offline'
}
localObject.on('status', this.statusCallback);
localObject.on('status', (statusCallback: onStatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId);
// Service processing.
});
```
10. Save a distributed data object and revoke the data saving operation.
10. Save a distributed data object and revoke the data saved.
```js
// Save the data object if the device on the network needs to retrieve the object data after the application exits.
localObject.save('local').then((result) => {
localObject.save("local").then((result: distributedDataObject.SaveSuccessResponse) => {
console.info(`Succeeded in saving. SessionId:${result.sessionId},version:${result.version},deviceId:${result.deviceId}`);
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to save. Code:${err.code},message:${err.message}`);
});
// Revoke the save of a distributed data object.
localObject.revokeSave().then((result) => {
// Revoke the data saved.
localObject.revokeSave().then((result: distributedDataObject.RevokeSaveSuccessResponse) => {
console.info(`Succeeded in revokeSaving. Session:${result.sessionId}`);
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Failed to revokeSave. Code:${err.code},message:${err.message}`);
});
```
11. Unsubscribe from the status changes of a distributed data object. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all status change callbacks of this distributed data object.
```js
interface offStatusCallback {
sessionId: string,
deviceId: string,
status: 'online' | 'offline'
}
// Unregister this.statusCallback.
localObject.off('status', this.statusCallback);
localObject.off('status', (statusCallback: offStatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId);
// Service processing.
});
// Unregister all status change callbacks.
localObject.off('status');
```
12. Remove a distributed data object from the synchronization network. The data of the removed distributed data object will not be synchronized to other devices.
```js
localObject.setSessionId(() => {
console.info('leave all lession.');
console.info('leave all session.');
});
```
```
\ No newline at end of file
......@@ -23,10 +23,10 @@ Creates a distributed data object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | Context | Yes| Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| source | object | Yes| Attributes of the distributed data object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | Context | Yes| Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| source | object | Yes| Attributes of the distributed data object.|
**Return value**
......@@ -42,10 +42,20 @@ FA model:
// Import the module.
import distributedObject from '@ohos.data.distributedDataObject';
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base';
// Obtain the context.
let context = featureAbility.getContext();
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types.
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
interface sourceObject{
name: string,
age: number,
isVis: boolean
}
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
let g_object: distributedObject.DataObject = distributedObject.create(context, source);
```
Stage model:
......@@ -54,13 +64,23 @@ Stage model:
// Import the module.
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
let g_object = null;
import { BusinessError } from '@ohos.base';
import window from '@ohos.window';
let g_object: distributedObject.DataObject = null;
interface sourceObject{
name: string,
age: number,
isVis: boolean
}
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
// Create a distributed data object, which has attributes of the string, number, boolean, and object types.
g_object = distributedObject.create(this.context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
onWindowStageCreate(windowStage: window.WindowStage) {
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
g_object = distributedObject.create(this.context, source);
}
}
```
......@@ -75,15 +95,15 @@ Creates a random session ID.
**Return value**
| Type| Description|
| -------- | -------- |
| string | Session ID created.|
| Type| Description|
| -------- | -------- |
| string | Session ID created.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
let sessionId = distributedObject.genSessionId();
let sessionId: string = distributedObject.genSessionId();
```
## SaveSuccessResponse<sup>9+</sup>
......@@ -124,18 +144,18 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | Yes| ID of a distributed data object on a trusted network.|
| callback | AsyncCallback&lt;void&gt; | Yes| Asynchronous callback invoked when the session ID is successfully set.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | Yes| ID of a distributed data object on a trusted network.|
| callback | AsyncCallback&lt;void&gt; | Yes| Asynchronous callback invoked when the session ID is successfully set.|
**Error codes**
For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message|
| -------- | -------- |
| 15400001 | Create table failed.|
| ID| Error Message|
| -------- | -------- |
| 15400001 | Create table failed.|
**Example**
......@@ -158,17 +178,17 @@ Exits all joined sessions.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.|
**Error codes**
For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message|
| -------- | -------- |
| 15400001 | Create table failed.|
| ID| Error Message|
| -------- | -------- |
| 15400001 | Create table failed.|
**Example**
......@@ -179,7 +199,7 @@ g_object.setSessionId(distributedObject.genSessionId(), ()=>{
});
// Exit the distributed network.
g_object.setSessionId(() => {
console.info("leave all lession.");
console.info("leave all session.");
});
```
......@@ -195,9 +215,9 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
**Return value**
......@@ -209,9 +229,9 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message|
| -------- | -------- |
| 15400001 | Create table failed.|
| ID| Error Message|
| -------- | -------- |
| 15400001 | Create table failed.|
**Example**
......@@ -219,13 +239,13 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId()).then (()=>{
console.info("join session.");
}).catch((error)=>{
}).catch((error: BusinessError)=>{
console.info("error:" + error.code + error.message);
});
// Exit the distributed network.
g_object.setSessionId().then (()=>{
console.info("leave all lession.");
}).catch((error)=>{
console.info("leave all session.");
}).catch((error: BusinessError)=>{
console.info("error:" + error.code + error.message);
});
```
......@@ -240,23 +260,26 @@ Subscribes to data changes of this distributed data object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback invoked to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback invoked to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example**
```js
globalThis.changeCallback = (sessionId, changeData) => {
console.info("change" + sessionId);
if (changeData != null && changeData != undefined) {
changeData.forEach(element => {
console.info("changed !" + element + " " + g_object[element]);
});
}
interface ChangeCallback {
sessionId: string,
fields: Array<string>
}
g_object.on("change", globalThis.changeCallback);
g_object.on("change", (changeData: ChangeCallback) => {
console.info("change" + changeData.sessionId);
if (changeData.fields != null && changeData.fields != undefined) {
for (let index: number = 0; index < changeData.fields.length; index++) {
console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]);
}
}
});
```
### off('change')<sup>9+</sup>
......@@ -269,17 +292,24 @@ Unsubscribes from the data changes of this distributed data object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example**
```js
// Unregister the specified data change callback.
g_object.off("change", globalThis.changeCallback);
g_object.off("change", (changeData:ChangeCallback) => {
console.info("change" + changeData.sessionId);
if (changeData.fields != null && changeData.fields != undefined) {
for (let index: number = 0; index < changeData.fields.length; index++) {
console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]);
}
}
});
// Unregister all data change callbacks.
g_object.off("change");
```
......@@ -294,18 +324,23 @@ Subscribes to status changes of this distributed data object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** indicates the object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** indicates the object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
**Example**
```js
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
interface onStatusCallback {
sessionId: string,
networkId: string,
status: 'online' | 'offline'
}
g_object.on("status", globalThis.statusCallback);
g_object.on("status", (statusCallback:onStatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId);
});
```
### off('status')<sup>9+</sup>
......@@ -318,20 +353,24 @@ Unsubscribes from the status change of this distributed data object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.|
**Example**
```js
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
interface offStatusCallback {
sessionId: string,
networkId: string,
status: 'online' | 'offline'
}
// Unregister the specified status change callback.
g_object.off("status",globalThis.statusCallback);
g_object.off("status", (statusCallback:StatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId);
});
// Unregister all status change callbacks.
g_object.off("status");
```
......@@ -354,16 +393,16 @@ The saved data will be released in the following cases:
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example**
```ts
g_object.setSessionId("123456");
g_object.save("local", (err, result) => {
g_object.save("local", (err: BusinessError, result:distributedObject.SaveSuccessResponse) => {
if (err) {
console.info("save failed, error code = " + err.code);
console.info("save failed, error message: " + err.message);
......@@ -394,26 +433,26 @@ The saved data will be released in the following cases:
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example**
```js
g_object.setSessionId("123456");
g_object.save("local").then((result) => {
g_object.save("local").then((result: distributedObject.SaveSuccessResponse) => {
console.info("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}).catch((err) => {
}).catch((err: BusinessError) => {
console.info("save failed, error code = " + err.code);
console.info("save failed, error message: " + err.message);
});
......@@ -432,16 +471,16 @@ If the object is stored on another device, the data on the local device will be
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example**
```js
g_object.setSessionId("123456");
// Save data for persistence.
g_object.save("local", (err, result) => {
g_object.save("local", (err: BusinessError, result: distributedObject.SaveSuccessResponse) => {
if (err) {
console.info("save failed, error code = " + err.code);
console.info("save failed, error message: " + err.message);
......@@ -453,7 +492,7 @@ g_object.save("local", (err, result) => {
console.info("save deviceId: " + result.deviceId);
});
// Delete the persistence data.
g_object.revokeSave((err, result) => {
g_object.revokeSave((err: BusinessError, result: distributedObject.RevokeSaveSuccessResponse) => {
if (err) {
console.info("revokeSave failed, error code = " + err.code);
console.info("revokeSave failed, error message: " + err.message);
......@@ -477,29 +516,29 @@ If the object is stored on another device, the data on the local device will be
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example**
```ts
g_object.setSessionId("123456");
// Save data for persistence.
g_object.save("local").then((result) => {
// Save data for persistence.
g_object.save("local").then((result: distributedObject.SaveSuccessResponse) => {
console.info("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}).catch((err) => {
}).catch((err: BusinessError) => {
console.info("save failed, error code = " + err.code);
console.info("save failed, error message: " + err.message);
});
// Delete the persistence data.
g_object.revokeSave().then((result) => {
g_object.revokeSave().then((result: distributedObject.RevokeSaveSuccessResponse) => {
console.info("revokeSave callback");
console.info("sessionId" + result.sessionId);
}).catch((err)=> {
}).catch((err: BusinessError)=> {
console.info("revokeSave failed, error code = " + err.code);
console.info("revokeSave failed, error message = " + err.message);
});
......@@ -520,9 +559,9 @@ Creates a distributed data object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | object | Yes| Attributes of the distributed data object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | object | Yes| Attributes of the distributed data object.|
**Return value**
......@@ -534,8 +573,17 @@ Creates a distributed data object.
```js
import distributedObject from '@ohos.data.distributedDataObject';
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types.
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
interface sourceObject{
name: string,
age: number,
isVis: boolean
}
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source);
```
## DistributedObject<sup>(deprecated)</sup>
......@@ -558,21 +606,31 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});;
interface sourceObject{
name: string,
age: number,
isVis: boolean
}
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source);
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId());
// Remove g_object from the distributed network.
......@@ -593,25 +651,38 @@ Subscribes to data changes of this distributed data object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback invoked to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback invoked to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.changeCallback = (sessionId, changeData) => {
console.info("change" + sessionId);
if (changeData != null && changeData != undefined) {
changeData.forEach(element => {
console.info("changed !" + element + " " + g_object[element]);
});
}
interface sourceObject{
name: string,
age: number,
isVis: boolean
}
interface ChangeCallback {
sessionId: string,
fields: Array<string>
}
g_object.on("change", globalThis.changeCallback);
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source);
g_object.on("change", (changeData:ChangeCallback) => {
console.info("change" + changeData.sessionId);
if (changeData.fields != null && changeData.fields != undefined) {
for (let index: number = 0; index < changeData.fields.length; index++) {
console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]);
}
}
});
```
### off('change')<sup>(deprecated)</sup>
......@@ -628,19 +699,40 @@ Unsubscribes from the data changes of this distributed data object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
interface sourceObject{
name: string,
age: number,
isVis: boolean
}
interface ChangeCallback {
sessionId: string,
fields: Array<string>
}
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source);
// Unregister the specified data change callback.
g_object.off("change", globalThis.changeCallback);
g_object.off("change", (changeData:ChangeCallback) => {
console.info("change" + changeData.sessionId);
if (changeData.fields != null && changeData.fields != undefined) {
for (let index: number = 0; index < changeData.fields.length; index++) {
console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]);
}
}
});
// Unregister all data change callbacks.
g_object.off("change");
```
......@@ -659,20 +751,36 @@ Subscribes to status changes of this distributed data object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** indicates the object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** indicates the object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
interface sourceObject{
name: string,
age: number,
isVis: boolean
}
interface StatusCallback {
sessionId: string,
networkId: string,
status: 'online' | 'offline'
}
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
g_object.on("status", globalThis.statusCallback);
let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source);
g_object.on("status", (statusCallback:StatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId);
});
```
### off('status')<sup>(deprecated)</sup>
......@@ -689,8 +797,8 @@ Unsubscribes from the status change of this distributed data object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.|
......@@ -699,12 +807,26 @@ Unsubscribes from the status change of this distributed data object.
```js
import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
interface sourceObject{
name: string,
age: number,
isVis: boolean
}
interface offStatusCallback {
sessionId: string,
deviceId: string,
status: 'online' | 'offline'
}
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source);
// Unregister the specified status change callback.
g_object.off("status",globalThis.statusCallback);
g_object.off("status", (statusCallback:offStatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId);
});
// Unregister all status change callbacks.
g_object.off("status");
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册