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

## When to Use

5 6 7
Distributed data objects allow data traversing across devices to be processed like local variables by shielding complex data interaction between devices. For the devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other devices. The devices can listen for data changes and online and offline status changes of other devices. 

The distributed data objects support basic data types, such as number, string, and Boolean, as well as complex data types, such as array and nested basic types.
A
annie_wangli 已提交
8 9 10 11


## Available APIs

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

A
annie_wangli 已提交
14 15 16 17 18 19
### 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
20
| Package | API | Description |
A
Annie_wang 已提交
21
| -------- | -------- | -------- |
22
| 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 已提交
23 24 25 26 27 28

### 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
29
| Package | API | Description |
A
Annie_wang 已提交
30 31
| -------- | -------- | -------- |
| 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 已提交
32 33 34

### Setting a SessionID for Distributed Data Objects

A
Annie_wang 已提交
35
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 已提交
36 37

**Table 3** API for setting a session ID
A
Annie_wang 已提交
38 39
| Class| API| Description|
| -------- | -------- | -------- |
40
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<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 已提交
41 42 43

### Observing Data Changes

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

**Table 4** APIs for observing data changes of a distributed data object
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.|
50
| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes.<br>**Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.|
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
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 66 67 68 69 70 71 72 73 74
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.

Call **revokeSave()** to revoke 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.

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.

**Table 6** APIs for saving a distributed data object and revoking the saving
75
| Class | API | Description |
A
Annie_wang 已提交
76
| -------- | -------- | -------- |
77 78
| DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object. This API uses a promise to return the result. |
| DistributedDataObject | save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object. This API uses an asynchronous callback to return the result. |
A
Annie_wang 已提交
79
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result. |
80
| DistributedDataObject | revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result. |
A
annie_wangli 已提交
81 82 83

## How to Develop

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

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

A
Annie_wang 已提交
88 89
   ```js   
   import distributedObject from '@ohos.data.distributedDataObject';   
A
annie_wangli 已提交
90
   ```
A
Annie_wang 已提交
91
   
92
2. Request the permission. 
A
Annie_wang 已提交
93
   
94
    Add the required permission in the **config.json** file. The sample code is as follows:
A
Annie_wang 已提交
95
    
A
Annie_wang 已提交
96 97 98 99 100 101 102 103 104 105 106
    ```
     {
       "module": {
           "reqPermissions": [
               {
                  "name": "ohos.permission.DISTRIBUTED_DATASYNC"
               }
           ]
       }
     }
    ```
A
Annie_wang 已提交
107 108 109
	This permission must also be authorized by the user through a dialog box when the application is started for the first time. The sample code is as follows:
    
    ```
A
Annie_wang 已提交
110
    import featureAbility from '@ohos.ability.featureAbility';
A
Annie_wang 已提交
111
    
A
Annie_wang 已提交
112 113 114 115 116 117 118
    function grantPermission() {
        console.info('grantPermission');
        let context = featureAbility.getContext();
        context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
            console.info(`result.requestCode=${result.requestCode}`)
    
        })
A
Annie_wang 已提交
119
    console.info('end grantPermission');
A
Annie_wang 已提交
120 121 122
    }
    grantPermission();
    ```
A
Annie_wang 已提交
123 124 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 131 132
   ```js
   var local_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, 
                  parent:undefined, list:undefined});
A
annie_wangli 已提交
133
   var sessionId = distributedObject.genSessionId();
A
annie_wangli 已提交
134 135 136
   ```


A
Annie_wang 已提交
137 138 139
4. Add the synchronization network. The data objects in the synchronization network include the local and remote objects.
   
   The sample code is as follows:
A
annie_wangli 已提交
140 141 142 143

   ```js
   // Local object
   var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true, 
A
Annie_wang 已提交
144
       parent:{mother:"jack mom", father:"jack Dad"}, list:[{mother:"jack mom"}, {father:"jack Dad"}]});
A
annie_wangli 已提交
145
   local_object.setSessionId(sessionId);
A
annie_wangli 已提交
146 147 148 149
   
   // Remote object
   var remote_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, 
                  parent:undefined, list:undefined});
A
annie_wangli 已提交
150
   remote_object.setSessionId(sessionId);
A
Annie_wang 已提交
151
   // After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
A
annie_wangli 已提交
152 153
   ```
   
A
Annie_wang 已提交
154
5. Observe the data changes of the distributed data object. 
A
Annie_wang 已提交
155

A
Annie_wang 已提交
156 157
   You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes.
   
A
Annie_wang 已提交
158 159
   The sample code is as follows:
   
A
annie_wangli 已提交
160
   ```js
A
annie_wangli 已提交
161
   function changeCallback(sessionId, changeData) {
A
annie_wangli 已提交
162 163 164 165 166 167
        console.info("change" + sessionId);
   
        if (changeData != null && changeData != undefined) {
            changeData.forEach(element => {
                console.info("changed !" + element + " " + local_object[element]);
        });
A
Annie_wang 已提交
168
     }
A
annie_wangli 已提交
169
    } 
A
Annie_wang 已提交
170
   
A
Annie_wang 已提交
171 172
    // To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
    local_object.on("change", this.changeCallback.bind(this));
A
annie_wangli 已提交
173 174
   ```
   
A
Annie_wang 已提交
175 176 177 178
6. Modify object attributes. 

   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 已提交
179
   The sample code is as follows:
A
annie_wangli 已提交
180 181 182 183
   ```js
   local_object.name = "jack";
   local_object.age = 19;
   local_object.isVis = false;
A
Annie_wang 已提交
184
   local_object.parent = {mother:"jack mom", father:"jack Dad"};
A
annie_wangli 已提交
185 186 187
   local_object.list = [{mother:"jack mom"}, {father:"jack Dad"}];
   ```

A
Annie_wang 已提交
188 189 190 191 192 193
   > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
   > 
   > 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_wangli 已提交
194 195 196 197 198 199 200
   ```js
   // Supported modification.
   local_object.parent = {mother:"mom", father:"dad"};
   // Modification not supported.
   local_object.parent.mother = "mom";
   ```

A
Annie_wang 已提交
201 202 203 204
7. Access the distributed data object. 

   Obtain the distributed data object attribute, which is the latest data on the network.

A
Annie_wang 已提交
205
   The sample code is as follows:
A
annie_wangli 已提交
206 207 208
   ```js
   console.info("name " + local_object["name"]); 
   ```
A
Annie_wang 已提交
209 210 211 212

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

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

A
annie_wangli 已提交
216
   ```js
A
Annie_wang 已提交
217
   // Unregister the specified data change callback.
A
annie_wangli 已提交
218
   local_object.off("change", changeCallback);
A
Annie_wang 已提交
219
   // Unregister all data change callbacks. 
A
annie_wangli 已提交
220 221
   local_object.off("change"); 
   ```
A
Annie_wang 已提交
222

A
Annie_wang 已提交
223
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.
224

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

A
annie_wangli 已提交
227
   ```js
A
Annie_wang 已提交
228
    function statusCallback(sessionId, networkId, status) {
A
annie_wangli 已提交
229 230 231
      this.response += "status changed " + sessionId + " " + status + " " + networkId;
    }
   
A
Annie_wang 已提交
232
    local_object.on("status", this.statusCallback);
A
annie_wangli 已提交
233
   ```
234

A
Annie_wang 已提交
235 236 237
10. Save a distributed data object and revoke the data saving operation.

    - Callback
A
Annie_wang 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

      ```
      ​```js
       // Save a distributed data object.
       local_object.save("local", (result, data) => {
           console.log("save callback");
           console.info("save sessionId " + data.sessionId);
           console.info("save version " + data.version);
           console.info("save deviceId " + data.deviceId);
       });
       // Revoke the data saving operation.
       local_object.revokeSave((result, data) => {
       console.log("revokeSave callback");
       console.info("revokeSave sessionId " + data.sessionId);
       });
      ​```
      ```

    - Promise

      ```
      ​```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.");
       });
      ​```
      ```

      

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

    You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object.
A
Annie_wang 已提交
282 283

    The sample code is as follows:
A
Annie_wang 已提交
284
    ```js
A
Annie_wang 已提交
285 286 287 288
    // Unregister the specified status change callback.
    local_object.off("status", this.statusCallback);
    // Unregister all status change callbacks.
    local_object.off("status");
A
Annie_wang 已提交
289 290
    ```

A
Annie_wang 已提交
291 292 293 294 295 296
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.

     The sample code is as follows:
       ```js
       local_object.setSessionId("");
       ```