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

## When to Use

A
Annie_wang 已提交
5
The distributed data objects allow data 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 the data changes and online and offline status 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 已提交
6 7 8 9


## Available APIs

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

### 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 已提交
27 28 29
| Package| API| Description|
| -------- | -------- | -------- |
| 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 已提交
30 31 32

### Setting a SessionID for Distributed Data Objects

A
Annie_wang 已提交
33
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 已提交
34 35

**Table 3** API for setting a session ID
A
Annie_wang 已提交
36 37
| Class| API| Description|
| -------- | -------- | -------- |
A
Annie_wang 已提交
38
| 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 已提交
39 40 41 42 43 44

### Observing Data Changes

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.

**Table 4** APIs for observing data changes of a distributed data object
A
Annie_wang 已提交
45
| Class| API| Description| 
A
Annie_wang 已提交
46
| -------- | -------- | -------- |
A
Annie_wang 已提交
47
| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.| 
A
Annie_wang 已提交
48
| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes. **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 已提交
49 50 51 52 53 54

### 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 已提交
55 56 57 58
| Class| API| Description|
| -------- | -------- | -------- |
| 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 已提交
59

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

A
Annie_wang 已提交
62 63 64 65 66 67 68 69 70 71
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.

A
Annie_wang 已提交
72
**Table 6** APIs for saving a distributed data object and revoking the saving operation
A
Annie_wang 已提交
73 74 75 76
| Class| API| Description|
| -------- | -------- | -------- |
| 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 已提交
77 78
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result.|
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result.|
A
annie_wangli 已提交
79 80 81 82 83 84

## How to Develop

The following example shows how to implement a distributed data object synchronization.

1. Import the @ohos.data.distributedDataObject module to the development environment.
A
Annie_wang 已提交
85 86
   ```js   
   import distributedObject from '@ohos.data.distributedDataObject';   
A
annie_wangli 已提交
87
   ```
A
Annie_wang 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
2. Request the permission. <br>Add the required permission in the **config.json** file. The sample code is as follows:
    ```
     {
       "module": {
           "reqPermissions": [
               {
                  "name": "ohos.permission.DISTRIBUTED_DATASYNC"
               }
           ]
       }
     }
    ```
    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:
    ```js
    import featureAbility from '@ohos.ability.featureAbility';
	
    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_wangli 已提交
115

A
Annie_wang 已提交
116
3. Obtain a distributed data object instance.
A
annie_wangli 已提交
117

A
Annie_wang 已提交
118
   The sample code is as follows:
A
annie_wangli 已提交
119 120 121
   ```js
   var local_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, 
                  parent:undefined, list:undefined});
A
annie_wangli 已提交
122
   var sessionId = distributedObject.genSessionId();
A
annie_wangli 已提交
123 124 125
   ```


A
Annie_wang 已提交
126 127 128
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 已提交
129 130 131 132

   ```js
   // Local object
   var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true, 
A
annie_wangli 已提交
133 134
       parent:{mother:"jack mom",father:"jack Dad"},list:[{mother:"jack mom"}, {father:"jack Dad"}]});
   local_object.setSessionId(sessionId);
A
annie_wangli 已提交
135 136 137 138
   
   // Remote object
   var remote_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, 
                  parent:undefined, list:undefined});
A
annie_wangli 已提交
139
   remote_object.setSessionId(sessionId);
A
Annie_wang 已提交
140
   // 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 已提交
141 142
   ```
   
A
Annie_wang 已提交
143 144 145 146
5. Observe the data changes of the distributed data object. <br>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.

   The sample code is as follows:
   
A
annie_wangli 已提交
147
   ```js
A
annie_wangli 已提交
148
   function changeCallback(sessionId, changeData) {
A
annie_wangli 已提交
149 150 151 152 153 154 155 156
        console.info("change" + sessionId);
   
        if (changeData != null && changeData != undefined) {
            changeData.forEach(element => {
                console.info("changed !" + element + " " + local_object[element]);
        });
        }
    } 
A
Annie_wang 已提交
157

A
Annie_wang 已提交
158 159
    // To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
    local_object.on("change", this.changeCallback.bind(this));
A
annie_wangli 已提交
160 161
   ```
   
A
Annie_wang 已提交
162
6. Modify object attributes. <br>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 已提交
163 164
   
   The sample code is as follows:
A
annie_wangli 已提交
165 166 167 168 169 170 171 172
   ```js
   local_object.name = "jack";
   local_object.age = 19;
   local_object.isVis = false;
   local_object.parent = {mother:"jack mom",father:"jack Dad"};
   local_object.list = [{mother:"jack mom"}, {father:"jack Dad"}];
   ```

A
Annie_wang 已提交
173
   > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
A
annie_wangli 已提交
174 175 176 177 178 179 180 181
   > For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. Example:
   ```js
   // Supported modification.
   local_object.parent = {mother:"mom", father:"dad"};
   // Modification not supported.
   local_object.parent.mother = "mom";
   ```

A
Annie_wang 已提交
182 183 184
7. Access the distributed data object. <br>Obtain the distributed data object attribute, which is the latest data on the network.
   
   The sample code is as follows:
A
annie_wangli 已提交
185 186 187
   ```js
   console.info("name " + local_object["name"]); 
   ```
A
Annie_wang 已提交
188
8. Unsubscribe from data changes. <br>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.
189

A
Annie_wang 已提交
190
   The sample code is as follows:
A
annie_wangli 已提交
191
   ```js
A
Annie_wang 已提交
192
   // Unregister the specified data change callback.
A
annie_wangli 已提交
193
   local_object.off("change", changeCallback);
A
Annie_wang 已提交
194
   // Unregister all data change callbacks. 
A
annie_wangli 已提交
195 196
   local_object.off("change"); 
   ```
A
Annie_wang 已提交
197 198
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:
A
annie_wangli 已提交
199
   ```js
A
Annie_wang 已提交
200
    function statusCallback(sessionId, networkId, status) {
A
annie_wangli 已提交
201 202 203
      this.response += "status changed " + sessionId + " " + status + " " + networkId;
    }
   
A
Annie_wang 已提交
204
    local_object.on("status", this.statusCallback);
A
annie_wangli 已提交
205
   ```
206

A
Annie_wang 已提交
207 208 209
10. Save a distributed data object and revoke the data saving operation.

    - Callback
A
Annie_wang 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    
       ```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. <br>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 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

    The sample code is as follows:
       ```js
    // Unregister the specified status change callback.
    local_object.off("status", this.statusCallback);
    // Unregister all status change callbacks.
    local_object.off("status");
       ```
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("");
       ```
## Development Example

The following example is provided for you to better understand the development of distributed data objects:

- [Distributed Notepad](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad)


When an event of the Notepad app occurs on a device, such as a note is added, the tile or content of a note is changed, or the event list is cleared, the change will be synchronized to other devices in the trusted network.