database-distributedobject-guidelines.md 11.8 KB
Newer Older
A
annie_wangli 已提交
1 2 3 4
# Distributed Data Object Development

## When to Use

A
Annie_wang 已提交
5
The **distributedDataObject** module provides APIs to implement data collaboration of the same application across multiple devices. In addition, the devices that form a Super Device can listen for object status and data changes with each other.
A
annie_wangli 已提交
6

A
Annie_wang 已提交
7
For example, when the data of the a distributed data object is added, deleted, or modified for application A on device 1, application A on device 2 can obtain the updated data. In addition, device 2 can listen for data changes and online/offline of the data objects on device 1.
A
annie_wangli 已提交
8 9 10

## Available APIs

A
Annie_wang 已提交
11
For details about the APIs, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
A
Annie_wang 已提交
12

A
annie_wangli 已提交
13 14 15 16 17 18
### Creating a Distributed Data Object Instance

Call **createDistributedObject()** to create a distributed data object instance. You can specify the attributes of the instance in **source**.


**Table 1** API for creating a distributed data object instance
A
Annie_wang 已提交
19
| Package| API| Description|
A
Annie_wang 已提交
20
| -------- | -------- | -------- |
21
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the **distributedObject** set.<br>- **DistributedObject**: returns the distributed object created.|
A
annie_wangli 已提交
22 23 24 25 26 27

### Generating a Session ID

Call **genSessionId()** to generate a session ID randomly. The generated session ID can be used to set the session ID of a distributed data object.

**Table 2** API for generating a session ID randomly
A
Annie_wang 已提交
28
| Package| API| Description|
A
Annie_wang 已提交
29 30
| -------- | -------- | -------- |
| ohos.data.distributedDataObject| genSessionId(): string | Generates a session ID, which can be used as the session ID of a distributed data object.|
A
annie_wangli 已提交
31

A
Annie_wang 已提交
32
### Setting a SessionID for a Distributed Data Object
A
annie_wangli 已提交
33

A
Annie_wang 已提交
34
Call **setSessionId()** to set a session ID for a distributed data object. The session ID is a unique identifier for one collaboration across devices. The distributed data objects to be synchronized must be associated with the same session ID.
A
annie_wangli 已提交
35 36

**Table 3** API for setting a session ID
A
Annie_wang 已提交
37 38
| Class| API| Description|
| -------- | -------- | -------- |
A
Annie_wang 已提交
39
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for a distributed data object.<br>**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
A
annie_wangli 已提交
40 41 42

### Observing Data Changes

A
Annie_wang 已提交
43
Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes.
A
annie_wangli 已提交
44 45

**Table 4** APIs for observing data changes of a distributed data object
A
Annie_wang 已提交
46 47

| Class| API| Description|
A
Annie_wang 已提交
48 49
| -------- | -------- | -------- |
| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.|
A
Annie_wang 已提交
50
| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes. **Callback**: specifies the data changes to unsubscribe from. If this parameter is not specified, all data changes of this distributed data object will be unsubscribed from.|
A
annie_wangli 已提交
51 52 53 54 55 56

### Observing Online or Offline Status

Call **on()** to subscribe to status changes of a distributed data object. The status can be online or offline. When the status changes, a callback will be invoked to return the status. You can use **off()** to unsubscribe from the status changes.

**Table 5** APIs for observing status changes of a distributed data object
A
Annie_wang 已提交
57
| Class| API| Description|
A
Annie_wang 已提交
58 59 60
| -------- | -------- | -------- |
| DistributedDataObject| on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }>): void | Subscribes to the status changes of a distributed data object.|
| DistributedDataObject| off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }>): void | Unsubscribes from status changes of a distributed data object.|
A
annie_wangli 已提交
61

A
Annie_wang 已提交
62
### Saving a Distributed Data Object and Revoking the Data Saving Operation
A
annie_wangli 已提交
63

A
Annie_wang 已提交
64 65
Call **save()** to save a distributed data object. When the application is active, the saved data will not be released. When the application exits and restarts, the data saved on the device will be restored.

A
Annie_wang 已提交
66
Call **revokeSave()** to delete a distributed data object that is no longer required. If the distributed data object is saved on the local device, **revokeSave()** will delete the data from all trusted devices. If the distributed data object is not saved on the local device, **revokeSave()** will delete the data from the local device.
A
Annie_wang 已提交
67 68 69 70 71 72 73

The saved data will be released in the following cases:

- The data is stored for more than 24 hours.
- The application has been uninstalled.
- Data is successfully restored.

A
Annie_wang 已提交
74 75
**Table 6** APIs for saving a distributed data object and revoking the saving operation
| Class| API| Description|
A
Annie_wang 已提交
76
| -------- | -------- | -------- |
A
Annie_wang 已提交
77 78
| DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object.|
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation.|
A
annie_wangli 已提交
79 80 81

## How to Develop

82
The following example shows how to implement distributed data object synchronization.
A
annie_wangli 已提交
83 84

1. Import the @ohos.data.distributedDataObject module to the development environment.
85

A
Annie_wang 已提交
86 87
   ```js   
   import distributedObject from '@ohos.data.distributedDataObject';   
A
annie_wangli 已提交
88
   ```
A
Annie_wang 已提交
89
   
A
Annie_wang 已提交
90 91 92 93 94
2. Apply for the permission.

   Add the required permission (FA model) in the **config.json** file. 

   The sample code is as follows:
A
Annie_wang 已提交
95
   
A
Annie_wang 已提交
96 97
   ```json
   {
A
Annie_wang 已提交
98 99 100 101 102 103 104 105
       "module": {
           "reqPermissions": [
               {
                  "name": "ohos.permission.DISTRIBUTED_DATASYNC"
               }
           ]
       }
     }
A
Annie_wang 已提交
106 107 108 109 110 111 112
   ```
   
   For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model).
   
   This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
   
   ```json
A
Annie_wang 已提交
113
    import featureAbility from '@ohos.ability.featureAbility';
A
Annie_wang 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
      
       function grantPermission() {
           console.info('grantPermission');
           let context = featureAbility.getContext();
           context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
               console.info(`result.requestCode=${result.requestCode}`)
       
           })
           console.info('end grantPermission');
       }
       
       grantPermission();
   ```
   
   

A
Annie_wang 已提交
130
3. Obtain a distributed data object instance.
A
annie_wangli 已提交
131

A
Annie_wang 已提交
132
   The sample code is as follows:
133

A
annie_wangli 已提交
134
   ```js
A
Annie_wang 已提交
135 136 137 138 139 140 141
   var local_object = distributedObject.createDistributedObject({
     name: undefined,
     age: undefined,
     isVis: true,
     parent: undefined,
     list: undefined
   });
A
annie_wangli 已提交
142
   var sessionId = distributedObject.genSessionId();
A
annie_wangli 已提交
143 144
   ```

A
Annie_wang 已提交
145
4. Add the distributed data object instance to the synchronization network. 
A
Annie_wang 已提交
146
   
A
Annie_wang 已提交
147
   The data objects in the synchronization network include the local and remote objects.
A
annie_wangli 已提交
148

A
Annie_wang 已提交
149 150
   The sample code is as follows:
   
A
annie_wangli 已提交
151 152
   ```js
   // Local object
A
Annie_wang 已提交
153 154 155 156 157 158 159
   var local_object = distributedObject.createDistributedObject({
     name: "jack",
     age: 18,
     isVis: true,
     parent: { mother: "jack mom", father: "jack Dad" },
     list: [{ mother: "jack mom" }, { father: "jack Dad" }]
   });
A
annie_wangli 已提交
160
   local_object.setSessionId(sessionId);
A
annie_wangli 已提交
161 162
   
   // Remote object
A
Annie_wang 已提交
163 164 165 166 167 168 169
   var remote_object = distributedObject.createDistributedObject({
     name: undefined,
     age: undefined,
     isVis: true,
     parent: undefined,
     list: undefined
   });
A
Annie_wang 已提交
170
   // After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
A
Annie_wang 已提交
171
   remote_object.setSessionId(sessionId);
A
annie_wangli 已提交
172 173
   ```
   
A
Annie_wang 已提交
174
5. Observe the data changes of the distributed data object. 
A
Annie_wang 已提交
175

A
Annie_wang 已提交
176 177
   You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be called to return the data changes.

A
Annie_wang 已提交
178
   The sample code is as follows:
A
Annie_wang 已提交
179

A
annie_wangli 已提交
180
   ```js
A
annie_wangli 已提交
181
   function changeCallback(sessionId, changeData) {
A
Annie_wang 已提交
182
       console.info("change" + sessionId);
A
annie_wangli 已提交
183
   
A
Annie_wang 已提交
184 185 186 187 188 189
       if (changeData != null && changeData != undefined) {
           changeData.forEach(element => {
               console.info("changed !" + element + " " + local_object[element]);
       });
       }
   } 
A
Annie_wang 已提交
190
   
A
Annie_wang 已提交
191 192
   // To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
   local_object.on("change", this.changeCallback.bind(this));
A
annie_wangli 已提交
193
   ```
A
Annie_wang 已提交
194 195

6. Modify attributes of the distributed data object. 
A
Annie_wang 已提交
196 197 198

   The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types).

A
Annie_wang 已提交
199
   The sample code is as follows:
A
Annie_wang 已提交
200

A
annie_wangli 已提交
201 202 203 204
   ```js
   local_object.name = "jack";
   local_object.age = 19;
   local_object.isVis = false;
A
Annie_wang 已提交
205 206
   local_object.parent = { mother: "jack mom", father: "jack Dad" };
   local_object.list = [{ mother: "jack mom" }, { father: "jack Dad" }];
A
annie_wangli 已提交
207 208
   ```

A
Annie_wang 已提交
209 210
   > **NOTE**<br>
   > For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. Example:
A
Annie_wang 已提交
211

A
annie_wangli 已提交
212 213
   ```js
   // Supported modification.
A
Annie_wang 已提交
214
   local_object.parent = { mother: "mom", father: "dad" };
A
annie_wangli 已提交
215 216 217 218
   // Modification not supported.
   local_object.parent.mother = "mom";
   ```

A
Annie_wang 已提交
219 220
7. Access the distributed data object. 

A
Annie_wang 已提交
221
   Obtain the distributed data object attributes, which are the latest data on the network.
A
Annie_wang 已提交
222

A
Annie_wang 已提交
223
   The sample code is as follows:
A
Annie_wang 已提交
224

A
annie_wangli 已提交
225 226 227
   ```js
   console.info("name " + local_object["name"]); 
   ```
A
Annie_wang 已提交
228 229 230 231

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.
232

A
Annie_wang 已提交
233
   The sample code is as follows:
234

A
annie_wangli 已提交
235
   ```js
A
Annie_wang 已提交
236
   // Unregister the specified data change callback.
A
annie_wangli 已提交
237
   local_object.off("change", changeCallback);
A
Annie_wang 已提交
238
   // Unregister all data change callbacks. 
A
annie_wangli 已提交
239 240
   local_object.off("change"); 
   ```
A
Annie_wang 已提交
241

A
Annie_wang 已提交
242 243
9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
   The sample code is as follows:
244

A
annie_wangli 已提交
245
   ```js
A
Annie_wang 已提交
246
    function statusCallback(sessionId, networkId, status) {
A
annie_wangli 已提交
247 248 249
      this.response += "status changed " + sessionId + " " + status + " " + networkId;
    }
   
A
Annie_wang 已提交
250
    local_object.on("status", this.statusCallback);
A
annie_wangli 已提交
251
   ```
252

A
Annie_wang 已提交
253 254
10. Save a distributed data object and revoke the data saving operation.

A
Annie_wang 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    ```js
    // Save a distributed data object.
    g_object.save("local").then((result) => {
      console.info("save sessionId " + result.sessionId);
      console.info("save version " + result.version);
      console.info("save deviceId " + result.deviceId);
    }, (result) => {
      console.info("save local failed.");
    });
    // Revoke the data saving operation.
    g_object.revokeSave().then((result) => {
      console.info("revokeSave success.");
    }, (result) => {
      console.info("revokeSave failed.");
    });
    ```
A
Annie_wang 已提交
271 272 273

11. Unsubscribe from the status changes of the distributed data object. 

A
Annie_wang 已提交
274
    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.
A
Annie_wang 已提交
275 276

    The sample code is as follows:
A
Annie_wang 已提交
277

A
Annie_wang 已提交
278
    ```js
A
Annie_wang 已提交
279 280 281 282
    // Unregister the specified status change callback.
    local_object.off("status", this.statusCallback);
    // Unregister all status change callbacks.
    local_object.off("status");
A
Annie_wang 已提交
283 284
    ```

A
Annie_wang 已提交
285
12. Remove a distributed data object from the synchronization network. 
A
Annie_wang 已提交
286

A
Annie_wang 已提交
287 288 289 290 291 292 293
    Data changes on the local object will not be synchronized to the removed distributed data object.

    The sample code is as follows:

    ```js
    local_object.setSessionId("");
    ```