database-distributedobject-guidelines.md 11.7 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 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
| -------- | -------- | -------- |
A
Annie_wang 已提交
21
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the distributed data object to set.<br>- **DistributedObject**: returns the distributed data 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 Session ID 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 data 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. <br/>**Callback**: callback to unregister. 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 or Deleting a Distributed Data Object
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 and deleting a distributed data object

A
Annie_wang 已提交
76
| Class| API| Description|
A
Annie_wang 已提交
77
| -------- | -------- | -------- |
A
Annie_wang 已提交
78
| DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object.|
A
Annie_wang 已提交
79
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Deletes a distributed data object. |
A
annie_wangli 已提交
80 81 82

## How to Develop

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

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

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

A
Annie_wang 已提交
93
   Add the permissions required (FA model) to the **config.json** file. The sample code is as follows:
A
Annie_wang 已提交
94

A
Annie_wang 已提交
95 96
    ```json
     {
A
Annie_wang 已提交
97 98 99 100 101 102 103 104
       "module": {
           "reqPermissions": [
               {
                  "name": "ohos.permission.DISTRIBUTED_DATASYNC"
               }
           ]
       }
     }
A
Annie_wang 已提交
105
    ```
A
Annie_wang 已提交
106
   For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model).
A
Annie_wang 已提交
107

A
Annie_wang 已提交
108
   This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
A
Annie_wang 已提交
109 110

    ```js
A
Annie_wang 已提交
111
    import featureAbility from '@ohos.ability.featureAbility';
A
Annie_wang 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124
	
    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 已提交
125
   
A
Annie_wang 已提交
126
3. Obtain a distributed data object instance.
A
annie_wangli 已提交
127

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

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

A
Annie_wang 已提交
141
4. Add the distributed data object instance to a network for data synchronization. The data objects in the synchronization network include the local and remote objects.
A
Annie_wang 已提交
142
   
A
Annie_wang 已提交
143
   The sample code is as follows:
A
Annie_wang 已提交
144

A
annie_wangli 已提交
145 146
   ```js
   // Local object
A
Annie_wang 已提交
147 148 149 150 151 152 153
   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 已提交
154
   local_object.setSessionId(sessionId);
A
annie_wangli 已提交
155 156
   
   // Remote object
A
Annie_wang 已提交
157 158 159 160 161 162 163
   var remote_object = distributedObject.createDistributedObject({
     name: undefined,
     age: undefined,
     isVis: true,
     parent: undefined,
     list: undefined
   });
A
Annie_wang 已提交
164
   // After learning that the local device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
A
Annie_wang 已提交
165
   remote_object.setSessionId(sessionId);
A
annie_wangli 已提交
166 167
   ```
   
A
Annie_wang 已提交
168
5. Observe the data changes of the distributed data object. 
A
Annie_wang 已提交
169

A
Annie_wang 已提交
170
   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 已提交
171
   
A
Annie_wang 已提交
172
   The sample code is as follows:
A
Annie_wang 已提交
173
   
A
annie_wangli 已提交
174
   ```js
A
annie_wangli 已提交
175
   function changeCallback(sessionId, changeData) {
A
Annie_wang 已提交
176
       console.info("change" + sessionId);
A
annie_wangli 已提交
177
   
A
Annie_wang 已提交
178 179 180 181
       if (changeData != null && changeData != undefined) {
           changeData.forEach(element => {
               console.info("changed !" + element + " " + local_object[element]);
       });
A
Annie_wang 已提交
182
    }
A
Annie_wang 已提交
183
   } 
A
Annie_wang 已提交
184
   
A
Annie_wang 已提交
185 186
   // To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
   local_object.on("change", this.changeCallback.bind(this));
A
annie_wangli 已提交
187
   ```
A
Annie_wang 已提交
188
   
A
Annie_wang 已提交
189
6. Modify attributes of the distributed data object. 
A
Annie_wang 已提交
190 191 192

   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 已提交
193
   The sample code is as follows:
A
Annie_wang 已提交
194

A
annie_wangli 已提交
195 196 197 198
   ```js
   local_object.name = "jack";
   local_object.age = 19;
   local_object.isVis = false;
A
Annie_wang 已提交
199 200
   local_object.parent = { mother: "jack mom", father: "jack Dad" };
   local_object.list = [{ mother: "jack mom" }, { father: "jack Dad" }];
A
annie_wangli 已提交
201 202
   ```

A
Annie_wang 已提交
203 204
   > **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 已提交
205

A
annie_wangli 已提交
206 207
   ```js
   // Supported modification.
A
Annie_wang 已提交
208
   local_object.parent = { mother: "mom", father: "dad" };
A
annie_wangli 已提交
209 210 211 212
   // Modification not supported.
   local_object.parent.mother = "mom";
   ```

A
Annie_wang 已提交
213 214
7. Access the distributed data object. 

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

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

A
annie_wangli 已提交
219 220 221
   ```js
   console.info("name " + local_object["name"]); 
   ```
A
Annie_wang 已提交
222 223 224 225

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

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

A
annie_wangli 已提交
229
   ```js
A
Annie_wang 已提交
230
   // Unregister the specified data change callback.
A
annie_wangli 已提交
231
   local_object.off("change", changeCallback);
A
Annie_wang 已提交
232
   // Unregister all data change callbacks. 
A
annie_wangli 已提交
233 234
   local_object.off("change"); 
   ```
A
Annie_wang 已提交
235

A
Annie_wang 已提交
236 237
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:
238

A
annie_wangli 已提交
239
   ```js
A
Annie_wang 已提交
240
    function statusCallback(sessionId, networkId, status) {
A
annie_wangli 已提交
241 242 243
      this.response += "status changed " + sessionId + " " + status + " " + networkId;
    }
   
A
Annie_wang 已提交
244
    local_object.on("status", this.statusCallback);
A
annie_wangli 已提交
245
   ```
246

A
Annie_wang 已提交
247
10. Save a distributed data object and delete it.
A
Annie_wang 已提交
248

A
Annie_wang 已提交
249 250 251 252 253 254 255 256 257
    ```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.");
    });
A
Annie_wang 已提交
258
    // Delete a distributed data object..
A
Annie_wang 已提交
259 260 261 262 263 264
    g_object.revokeSave().then((result) => {
      console.info("revokeSave success.");
    }, (result) => {
      console.info("revokeSave failed.");
    });
    ```
A
Annie_wang 已提交
265 266 267

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

A
Annie_wang 已提交
268
    You can specify the callback to unregister. If you do not specify the callback, all status change callbacks of this distributed data object will be unregistered.
A
Annie_wang 已提交
269 270

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

A
Annie_wang 已提交
272
    ```js
A
Annie_wang 已提交
273 274 275 276
    // Unregister the specified status change callback.
    local_object.off("status", this.statusCallback);
    // Unregister all status change callbacks.
    local_object.off("status");
A
Annie_wang 已提交
277 278
    ```

A
Annie_wang 已提交
279
12. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object.
A
Annie_wang 已提交
280 281 282 283 284 285

    The sample code is as follows:

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