1# @ohos.data.distributedDataObject (Distributed Data Object) 2 3The **distributedDataObject** module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. Although this module does not parse user data, you are advised not to transfer sensitive personal data or privacy data due to low-level security of storage path. 4 5> **NOTE** 6> 7> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. 8 9 10## Modules to Import 11 12```ts 13import { distributedDataObject } from '@kit.ArkData'; 14``` 15 16## distributedDataObject.create<sup>9+</sup> 17 18create(context: Context, source: object): DataObject 19 20Creates a distributed data object. The object properties support basic types (number, Boolean, and string) and complex types (array and nested basic types). 21 22**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 23 24**Parameters** 25 26 | Name| Type| Mandatory| Description| 27 | -------- | -------- | -------- | -------- | 28 | context | Context | Yes| Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).| 29 | source | object | Yes| Properties of the distributed data object.| 30 31**Return value** 32 33| Type| Description| 34| -------- | -------- | 35| [DataObject](#dataobject) | Distributed data object created.| 36 37**Error codes** 38 39 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 40 41 | ID| Error Message| 42 | -------- | -------- | 43 | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 44 45**Example** 46 47FA model: 48<!--code_no_check_fa--> 49```ts 50// Import the module. 51import { featureAbility } from '@kit.AbilityKit'; 52import { BusinessError } from '@kit.BasicServicesKit'; 53// Obtain the context. 54let context = featureAbility.getContext(); 55class SourceObject { 56 name: string 57 age: number 58 isVis: boolean 59 60 constructor(name: string, age: number, isVis: boolean) { 61 this.name = name; 62 this.age = age; 63 this.isVis = isVis; 64 } 65} 66 67let source: SourceObject = new SourceObject("jack", 18, false); 68let g_object: distributedDataObject.DataObject = distributedDataObject.create(context, source); 69``` 70 71Stage model: 72 73```ts 74// Import the module. 75import { UIAbility } from '@kit.AbilityKit'; 76import { BusinessError } from '@kit.BasicServicesKit'; 77import { window } from '@kit.ArkUI'; 78 79let g_object: distributedDataObject.DataObject|null = null; 80class SourceObject { 81 name: string 82 age: number 83 isVis: boolean 84 85 constructor(name: string, age: number, isVis: boolean) { 86 this.name = name; 87 this.age = age; 88 this.isVis = isVis; 89 } 90} 91 92class EntryAbility extends UIAbility { 93 onWindowStageCreate(windowStage: window.WindowStage) { 94 let source: SourceObject = new SourceObject("jack", 18, false); 95 g_object = distributedDataObject.create(this.context, source); 96 } 97} 98``` 99 100## distributedDataObject.genSessionId 101 102genSessionId(): string 103 104Creates a random session ID. 105 106**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 107 108**Return value** 109 110 | Type| Description| 111 | -------- | -------- | 112 | string | Session ID created.| 113 114**Example** 115 116```ts 117let sessionId: string = distributedDataObject.genSessionId(); 118``` 119 120## SaveSuccessResponse<sup>9+</sup> 121 122Represents the information returned by the callback of [save](#save9). 123 124**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 125 126| Name| Type| Mandatory| Description| 127| -------- | -------- | -------- | -------- | 128| sessionId | string | Yes| Unique ID for multi-device collaboration.| 129| version | number | Yes| Version of the saved object, which is a non-negative integer.| 130| deviceId | string | Yes| ID of the device where the distributed data object is stored. The value **local** indicates a local device.| 131 132## RevokeSaveSuccessResponse<sup>9+</sup> 133 134Represents the information returned by the callback of [revokeSave](#revokesave9). 135 136**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 137 138| Name| Type| Mandatory| Description| 139| -------- | -------- | -------- | -------- | 140| sessionId | string | Yes| Unique ID for multi-device collaboration.| 141 142## BindInfo<sup>11+</sup> 143 144Represents the information about the joint asset in the RDB store to bind. Currently, only the RDB stores are supported. 145 146**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 147 148 | Name | Type | Read-Only| Optional| Description | 149 | ---------- | ------------------------------------------------------------------ | ---- | ---- | ------------------------------------ | 150 | storeName | string | No | No | RDB store to which the target asset (asset to bind) belongs. | 151 | tableName | string | No | No | Table to which the target asset is located in the RDB store. | 152 | primaryKey | [commonType.ValuesBucket](js-apis-data-commonType.md#valuesbucket) | No | No | Primary key of the target asset in the RDB store. | 153 | field | string | No | No | Column in which the target asset is located in the RDB store. | 154 | assetName | string | No | No | Name of the target asset in the RDB store.| 155 156## DataObserver<sup>20+</sup> 157 158type DataObserver = (sessionId: string, fields: Array<string>) => void 159 160Defines an observer for obtaining the data change of a distributed object. 161 162**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 163 164| Name | Type | Mandatory| Description | 165| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | 166| sessionId | string | Yes | Session ID of the distributed data object, with a maximum length of 128 bytes. The value can contain only letters, digits, and underscores (_). | 167| fields | Array<string> | Yes | Changed properties of the distributed data object, with a maximum length of 128 bytes. The value can be customized and must be a non-empty string. | 168 169## StatusObserver<sup>20+</sup> 170 171type StatusObserver = (sessionId: string, networkId: string, status: string) => void 172 173Defines an observer for obtaining the status change of a distributed object. 174 175**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 176 177| Name| Type| Mandatory| Description| 178| -------- | -------- | -------- | -------- | 179| sessionId | string | Yes| Session ID of the distributed data object, with a maximum length of 128 bytes. The value can contain only letters, digits, and underscores (_).| 180| networkId | string | Yes| Network ID of the peer device, with a maximum of 255 bytes. The value must be a non-empty string.| 181| status | string | Yes| Status of the distributed object. The value can be **online**, **offline**, or **restore.**| 182 183## ProgressObserver<sup>20+</sup> 184 185type ProgressObserver = (sessionId: string, progress: number) => void 186 187Defines an observer for obtaining the transfer progress. 188 189**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 190 191| Name| Type| Mandatory| Description| 192| -------- | -------- | -------- | -------- | 193| sessionId | string | Yes| Session ID of the distributed data object, with a maximum length of 128 bytes. The value can contain only letters, digits, and underscores (_).| 194| progress | number | Yes| Asset transfer progress. The value is an integer ranging from -1 to 100. The value **-1** indicates that the progress fails to be obtained, and the value **100** indicates that the transfer is complete.| 195 196## DataObject 197 198Provides APIs for managing a distributed data object. Before using any API of this class, use [create()](#distributeddataobjectcreate9) to create a **DataObject** object. 199 200### setSessionId<sup>9+</sup> 201 202setSessionId(sessionId: string, callback: AsyncCallback<void>): void 203 204Sets a session ID. This API uses an asynchronous callback to return the result. For the devices in the collaboration state in a trusted network, data of the distributed objects with the same session ID can be automatically synced across devices. 205 206**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 207 208**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 209 210**Parameters** 211 212 | Name | Type | Mandatory| Description | 213 | --------- | ------------------------- | ---- | -------------------------------------------------------------------------------------------------------------- | 214 | sessionId | string | Yes | ID of a distributed data object on a trusted network. The value can contain only letters, digits, and underscores (_), and cannot exceed 128 characters. t If this parameter is set to "" or **null**, the distributed data object exits the network.| 215 | callback | AsyncCallback<void> | Yes | Asynchronous callback invoked when the session ID is successfully set. | 216 217**Error codes** 218 219 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md). 220 221 | ID| Error Message | 222 | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 223 | 201 | Permission verification failed. | 224 | 401 | Parameter error. Possible causes: 1. Incorrect parameter types; 2. The sessionId allows only letters, digits, and underscores(_), and cannot exceed 128 in length. | 225 | 15400001 | Failed to create the in-memory database. | 226 227**Example** 228 229```ts 230// Add g_object to the distributed network. 231g_object.setSessionId(distributedDataObject.genSessionId(), ()=>{ 232 console.info("join session"); 233}); 234// g_object exits the distributed network. 235g_object.setSessionId("", ()=>{ 236 console.info("leave all session"); 237}); 238``` 239 240### setSessionId<sup>9+</sup> 241 242setSessionId(callback: AsyncCallback<void>): void 243 244Exits all sessions. This API uses an asynchronous callback to return the result. 245 246**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 247 248**Parameters** 249 250 | Name| Type| Mandatory| Description| 251 | -------- | -------- | -------- | -------- | 252 | callback | AsyncCallback<void> | Yes| Callback invoked when the distributed data object exits all sessions.| 253 254**Error codes** 255 256 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md). 257 258 | ID| Error Message| 259 | -------- | -------- | 260 | 401 | Parameter error. Incorrect parameter types. | 261 | 15400001 | Failed to create the in-memory database. | 262 263**Example** 264 265```ts 266// Add g_object to the distributed network. 267g_object.setSessionId(distributedDataObject.genSessionId(), ()=>{ 268 console.info("join session"); 269}); 270// Exit the distributed network. 271g_object.setSessionId(() => { 272 console.info("leave all session."); 273}); 274``` 275 276### setSessionId<sup>9+</sup> 277 278setSessionId(sessionId?: string): Promise<void> 279 280Sets a session ID or exits the distributed network. This API uses a promise to return the result. If this parameter is set to "" or **null**, or left empty, the distributed data object exits the network. For the devices in the collaboration state in a trusted network, data of the distributed objects with the same session ID can be automatically synced across devices. 281 282**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 283 284**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 285 286**Parameters** 287 288 | Name | Type | Mandatory| Description | 289 | --------- | ------ | ---- | ---------------------------------------------------------------------------------------------------------------------------- | 290 | sessionId | string | No | ID of a distributed data object on a trusted network. The value can contain only letters, digits, and underscores (_), and cannot exceed 128 characters. If this parameter is set to "" or **null**, or left empty, the distributed data object exits the network.| 291 292**Return value** 293 294| Type| Description| 295| -------- | -------- | 296| Promise<void> | Promise that returns no value.| 297 298**Error codes** 299 300 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md). 301 302 | ID| Error Message | 303 | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 304 | 201 | Permission verification failed. | 305 | 401 | Parameter error. Possible causes: 1. Incorrect parameter types; 2. The sessionId allows only letters, digits, and underscores(_), and cannot exceed 128 in length. | 306 | 15400001 | Failed to create the in-memory database. | 307 308**Example** 309 310```ts 311// Add g_object to the distributed network. 312g_object.setSessionId(distributedDataObject.genSessionId()).then (()=>{ 313 console.info("join session."); 314 }).catch((error: BusinessError)=>{ 315 console.error("error:" + error.code + error.message); 316}); 317// Exit the distributed network. 318g_object.setSessionId().then (()=>{ 319 console.info("leave all session."); 320 }).catch((error: BusinessError)=>{ 321 console.error("error:" + error.code + error.message); 322}); 323``` 324 325### on('change')<sup>9+</sup> 326 327on(type: 'change', callback: (sessionId: string, fields: Array<string>) => void): void 328 329Subscribes to data changes of this distributed data object. 330 331**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 332 333**Parameters** 334 335| Name| Type| Mandatory| Description| 336| -------- | -------- | -------- | -------- | 337| type | string | Yes| Event type. The value is **'change'**, which indicates data changes.| 338| callback | (sessionId: string, fields: Array<string>) => void | Yes| Callback used 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 properties of the distributed data object.| 339 340**Error codes** 341 342 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 343 344 | ID| Error Message| 345 | -------- | -------- | 346 | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 347 348**Example** 349 350```ts 351g_object.on("change", (sessionId: string, fields: Array<string>) => { 352 console.info("change" + sessionId); 353 if (g_object != null && fields != null && fields != undefined) { 354 for (let index: number = 0; index < fields.length; index++) { 355 console.info("changed !" + fields[index] + " " + g_object[fields[index]]); 356 } 357 } 358}); 359``` 360 361### off('change')<sup>9+</sup> 362 363off(type: 'change', callback?: (sessionId: string, fields: Array<string>) => void): void 364 365Unsubscribes from data changes of this distributed data object. 366 367**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 368 369**Parameters** 370 371| Name| Type| Mandatory| Description| 372| -------- | -------- | -------- | -------- | 373| type | string | Yes| Event type. The value is **'change'**, which indicates data changes.| 374| callback | (sessionId: string, fields: Array<string>) => void | No| Callback to unregister. If this parameter is not specified, this API unsubscribes from all callbacks for data changes of this distributed object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed properties of the distributed data object.| 375 376**Error codes** 377 378 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 379 380 | ID| Error Message| 381 | -------- | -------- | 382 | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 383 384**Example** 385 386```ts 387// Unregister the specified data change callback. 388g_object.off("change", (sessionId: string, fields: Array<string>) => { 389 console.info("change" + sessionId); 390 if (g_object != null && fields != null && fields != undefined) { 391 for (let index: number = 0; index < fields.length; index++) { 392 console.info("changed !" + fields[index] + " " + g_object[fields[index]]); 393 } 394 } 395}); 396// Unregister all data change callbacks. 397g_object.off("change"); 398``` 399 400### on('status')<sup>9+</sup> 401 402on(type: 'status', callback: (sessionId: string, networkId: string, status: 'online' \| 'offline' ) => void): void 403 404Subscribes to status changes of this distributed data object. 405 406**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 407 408**Parameters** 409 410| Name| Type| Mandatory| Description| 411| -------- | -------- | -------- | -------- | 412| type | string | Yes| Event type. The value is **'status'**, which indicates the status change (online or offline) of the distributed object.| 413| callback | (sessionId: string, networkId: string, status: 'online' \| 'offline' ) => void | Yes| Callback used to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** identifies the device.<br>**status** indicates the object status, which can be online or offline.| 414 415**Error codes** 416 417 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 418 419 | ID| Error Message| 420 | -------- | -------- | 421 | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 422 423**Example** 424 425```ts 426g_object.on("status", (sessionId: string, networkId: string, status: 'online' | 'offline') => { 427 console.info("status changed " + sessionId + " " + status + " " + networkId); 428}); 429``` 430 431### off('status')<sup>9+</sup> 432 433off(type: 'status', callback?:(sessionId: string, networkId: string, status: 'online' \| 'offline') => void): void 434 435Unsubscribes from the status change of this distributed data object. 436 437**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 438 439**Parameters** 440 441| Name| Type| Mandatory| Description| 442| -------- | -------- | -------- | -------- | 443| type | string | Yes| Event type. The value is **'status'**, which indicates the status change (online or offline) of the distributed object.| 444| callback | (sessionId: string, networkId: string, status: 'online' \| 'offline' ) => void | No| Callback to unregister. If this parameter is not specified, this API unsubscribes from all callbacks for status changes of this distributed object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** identifies the distributed data object.<br>**status** indicates the object status, which can be online or offline.| 445 446**Error codes** 447 448 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 449 450 | ID| Error Message| 451 | -------- | -------- | 452 | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 453 454**Example** 455 456```ts 457// Unregister the specified status change callback. 458g_object.off("status", (sessionId: string, networkId: string, status: 'online' | 'offline') => { 459 console.info("status changed " + sessionId + " " + status + " " + networkId); 460}); 461// Unregister all status change callbacks. 462g_object.off("status"); 463``` 464 465### save<sup>9+</sup> 466 467save(deviceId: string, callback: AsyncCallback<SaveSuccessResponse>): void 468 469Saves a distributed data object. This API uses an asynchronous callback to return the result. 470 471If 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. 472 473The saved data will be released in the following cases: 474 475- The data is stored for more than 24 hours. 476- The application has been uninstalled. 477- Data is successfully restored. 478 479**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 480 481**Parameters** 482 483 | Name| Type| Mandatory| Description| 484 | -------- | -------- | -------- | -------- | 485 | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates a local device.| 486 | callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| 487 488**Error codes** 489 490 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 491 492 | ID| Error Message| 493 | -------- | -------- | 494 | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 495 | 801 | Capability not supported. | 496 497**Example** 498 499```ts 500g_object.setSessionId("123456"); 501g_object.save("local", (err: BusinessError, result:distributedDataObject.SaveSuccessResponse) => { 502 if (err) { 503 console.error("save failed, error code = " + err.code); 504 console.error("save failed, error message: " + err.message); 505 return; 506 } 507 console.info("save callback"); 508 console.info("save sessionId: " + result.sessionId); 509 console.info("save version: " + result.version); 510 console.info("save deviceId: " + result.deviceId); 511}); 512``` 513 514### save<sup>9+</sup> 515 516save(deviceId: string): Promise<SaveSuccessResponse> 517 518Saves a distributed data object. This API uses a promise to return the result. 519 520If 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. 521 522The saved data will be released in the following cases: 523 524- The data is stored for more than 24 hours. 525- The application has been uninstalled. 526- Data is successfully restored. 527 528**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 529 530**Parameters** 531 532 | Name| Type| Mandatory| Description| 533 | -------- | -------- | -------- | -------- | 534 | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates a local device. | 535 536**Return value** 537 538 | Type| Description| 539 | -------- | -------- | 540 | Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| 541 542**Error codes** 543 544 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 545 546 | ID| Error Message| 547 | -------- | -------- | 548 | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 549 | 801 | Capability not supported. | 550 551**Example** 552 553```ts 554g_object.setSessionId("123456"); 555g_object.save("local").then((callbackInfo: distributedDataObject.SaveSuccessResponse) => { 556 console.info("save callback"); 557 console.info("save sessionId " + callbackInfo.sessionId); 558 console.info("save version " + callbackInfo.version); 559 console.info("save deviceId " + callbackInfo.deviceId); 560}).catch((err: BusinessError) => { 561 console.error("save failed, error code = " + err.code); 562 console.error("save failed, error message: " + err.message); 563}); 564``` 565 566### revokeSave<sup>9+</sup> 567 568revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void 569 570Revokes the data of this distributed data object saved. This API uses an asynchronous callback to return the result. 571 572If the object is saved on the local device, the data saved on all trusted devices will be deleted. 573If the object is stored on another device, the data on the local device will be deleted. 574 575**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 576 577**Parameters** 578 579 | Name| Type| Mandatory| Description| 580 | -------- | -------- | -------- | -------- | 581 | callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Yes| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| 582 583**Error codes** 584 585 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 586 587 | ID| Error Message| 588 | -------- | -------- | 589 | 401 | Parameter error. Incorrect parameter types. | 590 | 801 | Capability not supported. | 591 592**Example** 593 594```ts 595g_object.setSessionId("123456"); 596// Save data for persistence. 597g_object.save("local", (err: BusinessError, result: distributedDataObject.SaveSuccessResponse) => { 598 if (err) { 599 console.error("save failed, error code = " + err.code); 600 console.error("save failed, error message: " + err.message); 601 return; 602 } 603 console.info("save callback"); 604 console.info("save sessionId: " + result.sessionId); 605 console.info("save version: " + result.version); 606 console.info("save deviceId: " + result.deviceId); 607}); 608// Delete the persistence data. 609g_object.revokeSave((err: BusinessError, result: distributedDataObject.RevokeSaveSuccessResponse) => { 610 if (err) { 611 console.error("revokeSave failed, error code = " + err.code); 612 console.error("revokeSave failed, error message: " + err.message); 613 return; 614 } 615 console.info("revokeSave callback"); 616 console.info("revokeSave sessionId " + result.sessionId); 617}); 618``` 619 620### revokeSave<sup>9+</sup> 621 622revokeSave(): Promise<RevokeSaveSuccessResponse> 623 624Revokes the data of this distributed data object saved. This API uses a promise to return the result. 625 626If the object is saved on the local device, the data saved on all trusted devices will be deleted. 627If the object is stored on another device, the data on the local device will be deleted. 628 629**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 630 631**Return value** 632 633 | Type| Description| 634 | -------- | -------- | 635 | Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| 636 637**Error codes** 638 639 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 640 641 | ID| Error Message| 642 | -------- | -------- | 643 | 801 | Capability not supported. | 644 645**Example** 646 647```ts 648g_object.setSessionId("123456"); 649// Save data for persistence. 650g_object.save("local").then((result: distributedDataObject.SaveSuccessResponse) => { 651 console.info("save callback"); 652 console.info("save sessionId " + result.sessionId); 653 console.info("save version " + result.version); 654 console.info("save deviceId " + result.deviceId); 655}).catch((err: BusinessError) => { 656 console.error("save failed, error code = " + err.code); 657 console.error("save failed, error message: " + err.message); 658}); 659// Delete the persistence data. 660g_object.revokeSave().then((result: distributedDataObject.RevokeSaveSuccessResponse) => { 661 console.info("revokeSave callback"); 662 console.info("sessionId" + result.sessionId); 663}).catch((err: BusinessError)=> { 664 console.error("revokeSave failed, error code = " + err.code); 665 console.error("revokeSave failed, error message = " + err.message); 666}); 667``` 668 669### bindAssetStore<sup>11+</sup> 670 671bindAssetStore(assetKey: string, bindInfo: BindInfo, callback: AsyncCallback<void>): void 672 673Binds joint assets. Currently, only the binding between an asset in a distributed data object and an asset in an RDB store is supported. This API uses an asynchronous callback to return the result. 674 675When an asset in a distributed object and an asset in an RDB store point to the same entity asset file, that is, the URIs of the two assets are the same, a conflict occurs. Such assets are called joint assets. To resolve the conflict, bind the joint assets. The binding is automatically released when the application exits the session. 676 677**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 678 679**Parameters** 680 681 | Name | Type | Mandatory| Description | 682 | -------- | ------------------------- | ---- | ---------------------------------------------------------------------------------- | 683 | assetKey | string | Yes | Key of the joint asset in the distributed data object. | 684 | bindInfo | [BindInfo](#bindinfo11) | Yes | Information about the joint asset in the RDB store, including the RDB store name, table name, primary key, column name, and asset name in the RDB store.| 685 | callback | AsyncCallback<void> | Yes | Callback used to return the result. | 686 687**Error codes** 688 689 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 690 691 | ID| Error Message| 692 | -------- | -------- | 693 | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 694 | 801 | Capability not supported. | 695 696**Example** 697 698```ts 699import { UIAbility } from '@kit.AbilityKit'; 700import { window } from '@kit.ArkUI'; 701import { commonType } from '@kit.ArkData'; 702import { BusinessError } from '@kit.BasicServicesKit'; 703 704class Note { 705 title: string | undefined 706 text: string | undefined 707 attachment: commonType.Asset | undefined 708 709 constructor(title: string | undefined, text: string | undefined, attachment: commonType.Asset | undefined) { 710 this.title = title; 711 this.text = text; 712 this.attachment = attachment; 713 } 714} 715 716class EntryAbility extends UIAbility { 717 onWindowStageCreate(windowStage: window.WindowStage) { 718 let attachment: commonType.Asset = { 719 name: 'test_img.jpg', 720 uri: 'file://com.example.myapplication/data/storage/el2/distributedfiles/dir/test_img.jpg', 721 path: '/dir/test_img.jpg', 722 createTime: '2024-01-02 10:00:00', 723 modifyTime: '2024-01-02 10:00:00', 724 size: '5', 725 status: commonType.AssetStatus.ASSET_NORMAL 726 } 727 let note: Note = new Note('test', 'test', attachment); 728 let g_object: distributedDataObject.DataObject = distributedDataObject.create(this.context, note); 729 g_object.setSessionId('123456'); 730 731 const bindInfo: distributedDataObject.BindInfo = { 732 storeName: 'notepad', 733 tableName: 'note_t', 734 primaryKey: { 735 'uuid': '00000000-0000-0000-0000-000000000000' 736 }, 737 field: 'attachment', 738 assetName: attachment.name as string 739 } 740 741 g_object.bindAssetStore('attachment', bindInfo, (err: BusinessError) => { 742 if (err) { 743 console.error('bindAssetStore failed.'); 744 } 745 console.info('bindAssetStore success.'); 746 }); 747 } 748} 749``` 750 751### bindAssetStore<sup>11+</sup> 752 753bindAssetStore(assetKey: string, bindInfo: BindInfo): Promise<void> 754 755Binds joint assets. Currently, only the binding between an asset in a distributed data object and an asset in an RDB store is supported. This API uses a promise to return the result. 756 757When an asset in a distributed object and an asset in an RDB store point to the same entity asset file, that is, the URIs of the two assets are the same, a conflict occurs. Such assets are called joint assets. To resolve the conflict, bind the joint assets. The binding is automatically released when the application exits the session. 758 759**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 760 761**Parameters** 762 763 | Name | Type | Mandatory| Description | 764 | -------- | ----------------------- | ---- | ---------------------------------------------------------------------------------- | 765 | assetKey | string | Yes | Key of the joint asset in the distributed data object. | 766 | bindInfo | [BindInfo](#bindinfo11) | Yes | Information about the joint asset in the RDB store, including the RDB store name, table name, primary key, column name, and asset name in the RDB store.| 767 768**Return value** 769 770 | Type | Description | 771 | ------------------- | ------------- | 772 | Promise<void> | Promise that returns no value.| 773 774**Error codes** 775 776 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 777 778 | ID| Error Message| 779 | -------- | -------- | 780 | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 781 | 801 | Capability not supported. | 782 783**Example** 784 785```ts 786import { UIAbility } from '@kit.AbilityKit'; 787import { window } from '@kit.ArkUI'; 788import { commonType } from '@kit.ArkData'; 789import { BusinessError } from '@kit.BasicServicesKit'; 790 791class Note { 792 title: string | undefined 793 text: string | undefined 794 attachment: commonType.Asset | undefined 795 796 constructor(title: string | undefined, text: string | undefined, attachment: commonType.Asset | undefined) { 797 this.title = title; 798 this.text = text; 799 this.attachment = attachment; 800 } 801} 802 803class EntryAbility extends UIAbility { 804 onWindowStageCreate(windowStage: window.WindowStage) { 805 let attachment: commonType.Asset = { 806 name: 'test_img.jpg', 807 uri: 'file://com.example.myapplication/data/storage/el2/distributedfiles/dir/test_img.jpg', 808 path: '/dir/test_img.jpg', 809 createTime: '2024-01-02 10:00:00', 810 modifyTime: '2024-01-02 10:00:00', 811 size: '5', 812 status: commonType.AssetStatus.ASSET_NORMAL 813 } 814 let note: Note = new Note('test', 'test', attachment); 815 let g_object: distributedDataObject.DataObject = distributedDataObject.create(this.context, note); 816 g_object.setSessionId('123456'); 817 818 const bindInfo: distributedDataObject.BindInfo = { 819 storeName: 'notepad', 820 tableName: 'note_t', 821 primaryKey: { 822 'uuid': '00000000-0000-0000-0000-000000000000' 823 }, 824 field: 'attachment', 825 assetName: attachment.name as string 826 } 827 828 g_object.bindAssetStore("attachment", bindInfo).then(() => { 829 console.info('bindAssetStore success.'); 830 }).catch((err: BusinessError) => { 831 console.error("bindAssetStore failed, error code = " + err.code); 832 }); 833 } 834} 835``` 836 837### on('change')<sup>20+</sup> 838 839on(type: 'change', callback: DataObserver): void 840 841Subscribes to data changes of this distributed data object. 842 843**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 844 845**Parameters** 846 847| Name| Type| Mandatory| Description| 848| -------- | -------- | -------- | -------- | 849| type | string | Yes| Event type. The value is **'change'**, which indicates data changes.| 850| callback | [DataObserver](#dataobserver20) | Yes| Callback used to listen for data changes of a distributed object.| 851 852**Example** 853 854```ts 855const changeCallback1: distributedDataObject.DataObserver = (sessionId: string, fields: Array<string>) => { 856 console.info("change callback1 " + sessionId); 857 if (fields != null && fields != undefined) { 858 for (let index: number = 0; index < fields.length; index++) { 859 console.info("change !" + fields[index]); 860 } 861 } 862} 863try { 864 g_object.on("change", changeCallback1); 865} catch (error) { 866 console.error("Execute failed, error code = " + error.code); 867} 868``` 869 870### off('change')<sup>20+</sup> 871 872off(type: 'change', callback?: DataObserver): void 873 874Unsubscribes from data changes of this distributed object. 875 876**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 877 878**Parameters** 879 880| Name| Type| Mandatory| Description| 881| -------- | -------- | -------- | -------- | 882| type | string | Yes| Event type. The value is **'change'**, which indicates data changes.| 883| callback | [DataObserver](#dataobserver20) | No| Callback to unregister. If this parameter is not specified, this API unsubscribes from all callbacks for data changes of this distributed object.| 884 885**Example** 886 887```ts 888const changeCallback1: distributedDataObject.DataObserver = (sessionId: string, fields: Array<string>) => { 889 console.info("change callback1 " + sessionId); 890 if (fields != null && fields != undefined) { 891 for (let index: number = 0; index < fields.length; index++) { 892 console.info("change !" + fields[index]); 893 } 894 } 895} 896 897const changeCallback2: distributedDataObject.DataObserver = (sessionId: string, fields: Array<string>) => { 898 console.info("change callback2 " + sessionId); 899 if (fields != null && fields != undefined) { 900 for (let index: number = 0; index < fields.length; index++) { 901 console.info("change !" + fields[index]); 902 } 903 } 904} 905 906try { 907 // Unregister a single data change callback function. 908 g_object.on("change", changeCallback1); 909 g_object.off("change", changeCallback1); 910 911 // Unregister all data change callback functions. 912 g_object.on("change", changeCallback1); 913 g_object.on("change", changeCallback2); 914 g_object.off("change"); 915} catch (error) { 916 console.error("Execute failed, error code = " + error.code); 917} 918``` 919 920### on('status')<sup>20+</sup> 921 922on(type: 'status', callback: StatusObserver): void 923 924Subscribes to the status changes of this distributed object. 925 926**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 927 928**Parameters** 929 930| Name| Type| Mandatory| Description| 931| -------- | -------- | -------- | -------- | 932| type | string | Yes| Event type. The value is **'status'**, which indicates the status changes of a distributed object.| 933| callback | [StatusObserver](#statusobserver20) | Yes| Callback used to listen for status changes of a distributed object.| 934 935**Example** 936 937```ts 938const statusCallback1: distributedDataObject.StatusObserver = (sessionId: string, networkId: string, status: string) => { 939 console.info("status callback " + sessionId); 940} 941try { 942 g_object.on("status", statusCallback1); 943} catch (error) { 944 console.error("Execute failed, error code = " + error.code); 945} 946``` 947 948### off('status')<sup>20+</sup> 949 950off(type: 'status', callback?: StatusObserver): void 951 952Unsubscribes from status changes of this distributed object. 953 954**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 955 956**Parameters** 957 958| Name| Type| Mandatory| Description| 959| -------- | -------- | -------- | -------- | 960| type | string | Yes| Event type. The value is **'status'**, which indicates the status changes of a distributed object.| 961| callback | [StatusObserver](#statusobserver20) | No| Callback to unregister. If this parameter is not specified, this API unsubscribes from all callbacks for status changes of this distributed object.| 962 963**Example** 964 965```ts 966const statusCallback1: distributedDataObject.StatusObserver = (sessionId: string, networkId: string, status: string) => { 967 console.info("status callback1" + sessionId); 968} 969 970const statusCallback2: distributedDataObject.StatusObserver = (sessionId: string, networkId: string, status: string) => { 971 console.info("status callback2" + sessionId); 972} 973try { 974 // Unregister a single status change callback function. 975 g_object.on("status", statusCallback1); 976 g_object.off("status", statusCallback1); 977 978 // Unregister all status change callback functions. 979 g_object.on("status", statusCallback1); 980 g_object.on("status", statusCallback2); 981 g_object.off("status"); 982} catch (error) { 983 console.error("Execute failed, error code = " + error.code); 984} 985``` 986 987### on('progressChanged')<sup>20+</sup> 988 989on(type: 'progressChanged', callback: ProgressObserver): void 990 991Subscribes to the asset transfer progress changes. 992 993**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 994 995**Parameters** 996 997| Name| Type| Mandatory| Description| 998| -------- | -------- | -------- | -------- | 999| type | string | Yes| Event type. The value is **'progressChanged'**, which indicates the asset transfer progress changes.| 1000| callback | [ProgressObserver](#progressobserver20) | Yes| Callback used to listen for the asset transfer progress changes.| 1001 1002**Example** 1003 1004```ts 1005const progressChangedCallback: distributedDataObject.ProgressObserver = (sessionId: string, progress: number) => { 1006 console.info("progressChanged callback" + sessionId); 1007 console.info("progressChanged callback" + progress); 1008} 1009try { 1010 g_object.on("progressChanged", progressChangedCallback); 1011} catch (error) { 1012 console.error("Execute failed, error code = " + error.code); 1013} 1014``` 1015 1016### off('progressChanged')<sup>20+</sup> 1017 1018off(type: 'progressChanged', callback?: ProgressObserver): void 1019 1020Unsubscribes from asset transfer progress changes. 1021 1022**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 1023 1024**Parameters** 1025 1026| Name| Type| Mandatory| Description| 1027| -------- | -------- | -------- | -------- | 1028| type | string | Yes| Event type. The value is **'progressChanged'**, which indicates the asset transfer progress changes.| 1029| callback | [ProgressObserver](#progressobserver20) | No| Callback to unregister. If this parameter is not specified, this API unsubscribes from all callbacks for progress changes of this distributed object.| 1030 1031**Example** 1032 1033```ts 1034const progressChangedCallback1: distributedDataObject.ProgressObserver = (sessionId: string, progress: number) => { 1035 console.info("progressChanged callback1" + sessionId); 1036 console.info("progressChanged callback1" + progress); 1037} 1038 1039const progressChangedCallback2: distributedDataObject.ProgressObserver = (sessionId: string, progress: number) => { 1040 console.info("progressChanged callback2" + sessionId); 1041 console.info("progressChanged callback2" + progress); 1042} 1043try { 1044 g_object.on("progressChanged", progressChangedCallback1); 1045 // Unsubscribes from the asset transfer progress changes. 1046 g_object.off("progressChanged", progressChangedCallback1); 1047 1048 g_object.on("progressChanged", progressChangedCallback1); 1049 g_object.on("progressChanged", progressChangedCallback2); 1050 // Unsubscribes from all asset transfer progress changes. 1051 g_object.off("progressChanged"); 1052} catch (error) { 1053 console.error("Execute failed, error code = " + error.code); 1054} 1055``` 1056### setAsset<sup>20+</sup> 1057 1058setAsset(assetKey: string, uri: string): Promise<void> 1059 1060Sets the property information about a single asset in a distributed object. This API must be called before the [setSessionId](#setsessionid9-2) API is called. This API uses a promise to return the result. 1061 1062> **NOTE** 1063> 1064> When setting an asset, ensure that the **assetKey** file exists and is of the asset type. Otherwise, the peer device may fail to receive the asset. 1065> 1066> When setting an asset, ensure that the URI is a correct and actual distributed path. Otherwise, the peer device may fail to receive the asset. 1067 1068The following table lists the exception scenarios. 1069 1070 | Scenario | Execution Results| 1071 | -------- | -------- | 1072 | The [setAsset](#setasset20) API is called to set an asset after the [setSessionId](#setsessionid9-2) API is called to set a session ID. | Error code 15400003 is thrown, indicating the asset setting failure.| 1073 | The value of **assetKey** is invalid, for example, **null**, **undefined**, or '' (empty). | Error code 15400002 is thrown, indicating the asset setting failure.| 1074 | **assetKey** exists, but the corresponding file is not of the asset type.| The system forcibly changes the file type to asset and sets the asset field. As a result, the actual asset may fail to be synchronized to the peer device.| 1075 | The value of **uri** is invalid, for example, **null**, **undefined**, or '' (empty). | Error code 15400002 is thrown, indicating the asset setting failure.| 1076 1077 1078**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 1079 1080**Parameters** 1081 1082 | Name | Type | Mandatory| Description | 1083 | -------- | ----------------------- | ---- | ---------------------------------------------------------------------------------- | 1084 | assetKey | string | Yes | Property name of the asset in the distributed object.<br>**Constraints**<br>(1) The corresponding **assetKey** file must exist and be of the [Asset](js-apis-data-commonType.md#asset) type. Otherwise, an asset setting error may occur.<br>(2) In the collaboration or continuation scenario, the corresponding **assetKey** file must exist and be of the asset type at both devices so that the asset can be synchronized to the peer device. | 1085 | uri | string | Yes | URI of the new asset to be set, indicating the distributed path for storing the existing asset.| 1086 1087**Return value** 1088 1089 | Type | Description | 1090 | ------------------- | ------------- | 1091 | Promise<void> | Promise that returns no value.| 1092 1093**Error codes** 1094 1095 For details about the error codes, see [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md). 1096 1097 | ID| Error Message| 1098 | -------- | -------- | 1099 | 15400002 | Parameter error. Possible causes: 1. The assetKey is invalid, such as ""; 2. The uri is invalid, such as "". | 1100 | 15400003 | The sessionId of the distributed object has been set. | 1101 1102**Example**: 1103 1104```ts 1105import { UIAbility } from '@kit.AbilityKit'; 1106import { window } from '@kit.ArkUI'; 1107import { BusinessError } from '@kit.BasicServicesKit'; 1108import { commonType, distributedDataObject } from '@kit.ArkData'; 1109 1110class Note { 1111 title: string | undefined 1112 text: string | undefined 1113 attachment: commonType.Asset | undefined 1114 1115 constructor(title: string | undefined, text: string | undefined, attachment: commonType.Asset | undefined) { 1116 this.title = title; 1117 this.text = text; 1118 this.attachment = attachment; 1119 } 1120} 1121 1122class EntryAbility extends UIAbility { 1123 onWindowStageCreate(windowStage: window.WindowStage) { 1124 let attachment: commonType.Asset = { 1125 name: 'test_img.jpg', 1126 uri: 'file://com.example.myapplication/data/storage/el2/distributedfiles/dir/test_img.jpg', 1127 path: '/dir/test_img.jpg', 1128 createTime: '2024-01-02 10:00:00', 1129 modifyTime: '2024-01-02 10:00:00', 1130 size: '5', 1131 status: commonType.AssetStatus.ASSET_NORMAL 1132 } 1133 let note: Note = new Note('test', 'test', attachment); 1134 let g_object: distributedDataObject.DataObject = distributedDataObject.create(this.context, note); 1135 1136 let uri = "file://test/test.img"; 1137 g_object.setAsset("attachment", uri).then(() => { 1138 console.info('setAsset success.'); 1139 }).catch((err: BusinessError) => { 1140 console.error("setAsset failed, error code = " + err.code); 1141 }); 1142 } 1143} 1144``` 1145 1146### setAssets<sup>20+</sup> 1147 1148setAssets(assetsKey: string, uris: Array<string>): Promise<void> 1149 1150Sets the property information about multiple assets in a distributed object. This API must be called before the [setSessionId](#setsessionid9-2) API is called. The number of values contained in the **uris** array ranges from 1 to 50. This API uses a promise to return the result. 1151 1152> **NOTE** 1153> 1154> When setting an asset, ensure that the **assetsKey** file exists and is of the asset type. Otherwise, the peer device may fail to receive the assets. 1155> 1156> When setting an asset, ensure that the URIs in the array are correct and actual distributed paths. Otherwise, the peer device may fail to receive the assets. 1157 1158The following table lists the exception scenarios. 1159 1160 | Scenario | Execution Results| 1161 | -------- | -------- | 1162 | The [setAssets](#setassets20) API is called to set an asset after the [setSessionId](#setsessionid9-2) API is called to set a session ID. | Error code 15400003 is thrown, indicating the asset setting failure.| 1163 | The value of **assetsKey** is invalid, for example, **null**, **undefined**, or '' (empty). | Error code 15400002 is thrown, indicating the asset setting failure.| 1164 | **assetsKey** exists, but the corresponding file is not of the asset type.| The system forcibly changes the file type to asset and sets the asset field. As a result, the actual asset may fail to be synchronized to the peer device.| 1165 | **assetsKey** exists and the corresponding file is of the asset type.| The asset is set successfully, and the URI information is updated.| 1166 | The number of URI elements in the **uris** array is 0 or greater than 50. | Error code 15400002 is thrown, indicating the asset setting failure.| 1167 | The number of URI elements in the **uris** array ranges from 1 to 50, and one or more URIs are invalid, for example, **null**, **undefined**, or '' (empty).| Error code 15400002 is thrown, indicating the asset setting failure.| 1168 1169**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 1170 1171**Parameters** 1172 1173 | Name | Type | Mandatory| Description | 1174 | -------- | ----------------------- | ---- | ---------------------------------------------------------------------------------- | 1175 | assetsKey | string | Yes | Property name of the assets in the distributed object.<br>**Constraints**<br>(1) The corresponding **assetsKey** file must exist and be of the [Asset](js-apis-data-commonType.md#asset) type. Otherwise, an asset setting error may occur.<br>(2) In the collaboration or continuation scenario, the corresponding **assetsKey** file must exist and be of the asset type at both devices so that the asset array can be synchronized to the peer device. | 1176 | uris | Array<string> | Yes | URIs of the new asset array to be set, indicating the distributed paths for storing each element of the asset. The number of array elements ranges from 1 to 50. The URI of an element must be the distributed path corresponding to an actual asset.| 1177 1178**Return value** 1179 1180 | Type | Description | 1181 | ------------------- | ------------- | 1182 | Promise<void> | Promise that returns no value.| 1183 1184**Error codes** 1185 1186 For details about the error codes, see [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md). 1187 1188 | ID| Error Message| 1189 | -------- | -------- | 1190 | 15400002 | Parameter error. Possible causes:1. The assetsKey is invalid, such as ""; 2. The uris is invalid, such as the length of uris is more than 50. | 1191 | 15400003 | The sessionId of the distributed object has been set. | 1192 1193**Example**: 1194 1195```ts 1196import { UIAbility } from '@kit.AbilityKit'; 1197import { window } from '@kit.ArkUI'; 1198import { BusinessError } from '@kit.BasicServicesKit'; 1199import { commonType, distributedDataObject } from '@kit.ArkData'; 1200 1201class Note { 1202 title: string | undefined 1203 text: string | undefined 1204 attachment: commonType.Asset | undefined 1205 1206 constructor(title: string | undefined, text: string | undefined, attachment: commonType.Asset | undefined) { 1207 this.title = title; 1208 this.text = text; 1209 this.attachment = attachment; 1210 } 1211} 1212 1213class EntryAbility extends UIAbility { 1214 onWindowStageCreate(windowStage: window.WindowStage) { 1215 let attachment: commonType.Asset = { 1216 name: 'test_img.jpg', 1217 uri: 'file://com.example.myapplication/data/storage/el2/distributedfiles/dir/test_img.jpg', 1218 path: '/dir/test_img.jpg', 1219 createTime: '2024-01-02 10:00:00', 1220 modifyTime: '2024-01-02 10:00:00', 1221 size: '5', 1222 status: commonType.AssetStatus.ASSET_NORMAL 1223 } 1224 let note: Note = new Note('test', 'test', attachment); 1225 let g_object: distributedDataObject.DataObject = distributedDataObject.create(this.context, note); 1226 1227 let uris: Array<string> = ["file://test/test_1.txt", "file://test/test_2.txt"]; 1228 g_object.setAssets("attachment", uris).then(() => { 1229 console.info('setAssets success.'); 1230 }).catch((err: BusinessError) => { 1231 console.error("setAssets failed, error code = " + err.code); 1232 }); 1233 } 1234} 1235``` 1236 1237## distributedDataObject.createDistributedObject<sup>(deprecated)</sup> 1238 1239createDistributedObject(source: object): DistributedObject 1240 1241 1242Creates a distributed data object. 1243 1244> **NOTE** 1245> 1246> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [distributedDataObject.create](#distributeddataobjectcreate9). 1247 1248**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 1249 1250**Parameters** 1251 1252 | Name| Type| Mandatory| Description| 1253 | -------- | -------- | -------- | -------- | 1254 | source | object | Yes| Properties of the distributed data object.| 1255 1256**Return value** 1257 1258| Type| Description| 1259| -------- | -------- | 1260| [DistributedObject](#distributedobjectdeprecated) | Distributed data object created.| 1261 1262**Example** 1263 1264```ts 1265class SourceObject { 1266 name: string 1267 age: number 1268 isVis: boolean 1269 1270 constructor(name: string, age: number, isVis: boolean) { 1271 this.name = name 1272 this.age = age 1273 this.isVis = isVis 1274 } 1275} 1276 1277let source: SourceObject = new SourceObject("jack", 18, false); 1278let g_object: distributedDataObject.DistributedObject = distributedDataObject.createDistributedObject(source); 1279``` 1280 1281## DistributedObject<sup>(deprecated)</sup> 1282 1283Provides APIs for managing a distributed data object. Before using any API of this class, use [createDistributedObject()](#distributeddataobjectcreatedistributedobjectdeprecated) to create a **DistributedObject** object. 1284 1285### setSessionId<sup>(deprecated)</sup> 1286 1287setSessionId(sessionId?: string): boolean 1288 1289Sets a session ID. For the devices in the collaboration state in a trusted network, data of the distributed objects with the same session ID can be automatically synced across devices. 1290 1291> **NOTE** 1292> 1293> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setSessionId](#setsessionid9). 1294 1295**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 1296 1297**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 1298 1299**Parameters** 1300 1301 | Name| Type| Mandatory| Description| 1302 | -------- | -------- | -------- | -------- | 1303 | 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.| 1304 1305**Return value** 1306 1307 | Type| Description| 1308 | -------- | -------- | 1309 | boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. | 1310 1311**Example** 1312 1313```ts 1314class SourceObject { 1315 name: string 1316 age: number 1317 isVis: boolean 1318 1319 constructor(name: string, age: number, isVis: boolean) { 1320 this.name = name 1321 this.age = age 1322 this.isVis = isVis 1323 } 1324} 1325 1326let source: SourceObject = new SourceObject("jack", 18, false); 1327let g_object: distributedDataObject.DistributedObject = distributedDataObject.createDistributedObject(source); 1328// Add g_object to the distributed network. 1329g_object.setSessionId(distributedDataObject.genSessionId()); 1330// Remove g_object from the distributed network. 1331g_object.setSessionId(""); 1332``` 1333 1334### on('change')<sup>(deprecated)</sup> 1335 1336on(type: 'change', callback: (sessionId: string, fields: Array<string>) => void): void 1337 1338Subscribes to data changes of this distributed data object. 1339 1340> **NOTE** 1341> 1342> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('change')](#onchange9). 1343 1344**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 1345 1346**Parameters** 1347 1348| Name| Type| Mandatory| Description| 1349| -------- | -------- | -------- | -------- | 1350| type | string | Yes| Event type. The value is **'change'**, which indicates data changes.| 1351| callback | (sessionId: string, fields: Array<string>) => void | Yes| Callback used 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 properties of the distributed data object.| 1352 1353**Example** 1354 1355```ts 1356class SourceObject { 1357 name: string 1358 age: number 1359 isVis: boolean 1360 1361 constructor(name: string, age: number, isVis: boolean) { 1362 this.name = name 1363 this.age = age 1364 this.isVis = isVis 1365 } 1366} 1367 1368let source: SourceObject = new SourceObject("jack", 18, false); 1369let g_object: distributedDataObject.DistributedObject = distributedDataObject.createDistributedObject(source); 1370g_object.on("change", (sessionId: string, fields: Array<string>) => { 1371 console.info("change" + sessionId); 1372 if (fields != null && fields != undefined) { 1373 for (let index: number = 0; index < fields.length; index++) { 1374 console.info("changed !" + fields[index] + " " + g_object[fields[index]]); 1375 } 1376 } 1377}); 1378``` 1379 1380### off('change')<sup>(deprecated)</sup> 1381 1382off(type: 'change', callback?: (sessionId: string, fields: Array<string>) => void): void 1383 1384Unsubscribes from data changes of this distributed data object. 1385 1386> **NOTE** 1387> 1388> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [off('change')](#offchange9). 1389 1390**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 1391 1392**Parameters** 1393 1394| Name| Type| Mandatory| Description| 1395| -------- | -------- | -------- | -------- | 1396| type | string | Yes| Event type. The value is **'change'**, which indicates data changes.| 1397| callback | (sessionId: string, fields: Array<string>) => void | No| Callback to unregister. If this parameter is not specified, this API unsubscribes from all callbacks for data changes of this distributed object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed properties of the distributed data object.| 1398 1399**Example** 1400 1401```ts 1402class SourceObject { 1403 name: string 1404 age: number 1405 isVis: boolean 1406 1407 constructor(name: string, age: number, isVis: boolean) { 1408 this.name = name 1409 this.age = age 1410 this.isVis = isVis 1411 } 1412} 1413 1414let source: SourceObject = new SourceObject("jack", 18, false); 1415let g_object: distributedDataObject.DistributedObject = distributedDataObject.createDistributedObject(source); 1416// Unregister the specified data change callback. 1417g_object.off("change", (sessionId: string, fields: Array<string>) => { 1418 console.info("change" + sessionId); 1419 if (fields != null && fields != undefined) { 1420 for (let index: number = 0; index < fields.length; index++) { 1421 console.info("changed !" + fields[index] + " " + g_object[fields[index]]); 1422 } 1423 } 1424}); 1425// Unregister all data change callbacks. 1426g_object.off("change"); 1427``` 1428 1429### on('status')<sup>(deprecated)</sup> 1430 1431on(type: 'status', callback: (sessionId: string, networkId: string, status: 'online' | 'offline' ) => void): void 1432 1433Subscribes to status changes of this distributed data object. 1434 1435> **NOTE** 1436> 1437> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('status')](#onstatus9). 1438 1439**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 1440 1441**Parameters** 1442 1443| Name| Type| Mandatory| Description| 1444| -------- | -------- | -------- | -------- | 1445| type | string | Yes| Event type. The value is **'status'**, which indicates the status change (online or offline) of the distributed object.| 1446| callback | (sessionId: string, networkId: string, status: 'online' \| 'offline' ) => void | Yes| Callback used to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** identifies the device.<br>**status** indicates the object status, which can be online or offline.| 1447 1448**Example** 1449 1450```ts 1451class SourceObject { 1452 name: string 1453 age: number 1454 isVis: boolean 1455 1456 constructor(name: string, age: number, isVis: boolean) { 1457 this.name = name 1458 this.age = age 1459 this.isVis = isVis 1460 } 1461} 1462 1463let source: SourceObject = new SourceObject("jack", 18, false); 1464let g_object: distributedDataObject.DistributedObject = distributedDataObject.createDistributedObject(source); 1465 1466g_object.on("status", (sessionId: string, networkId: string, status: 'online' | 'offline') => { 1467 console.info("status changed " + sessionId + " " + status + " " + networkId); 1468}); 1469``` 1470 1471### off('status')<sup>(deprecated)</sup> 1472 1473off(type: 'status', callback?: (sessionId: string, networkId: string, status: 'online' | 'offline' ) => void): void 1474 1475Unsubscribes from the status change of this distributed data object. 1476 1477> **NOTE** 1478> 1479> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [off('status')](#offstatus9). 1480 1481**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject 1482 1483**Parameters** 1484 1485| Name| Type| Mandatory| Description| 1486| -------- | -------- | -------- | -------- | 1487| type | string | Yes| Event type. The value is **'status'**, which indicates the status change (online or offline) of the distributed object.| 1488| callback | (sessionId: string, networkId: string, status: 'online' \| 'offline' ) => void | No| Callback to unregister. If this parameter is not specified, this API unsubscribes from all callbacks for status changes of this distributed object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** identifies the distributed data object.<br>**status** indicates the object status, which can be online or offline.| 1489 1490 1491**Example** 1492 1493```ts 1494class SourceObject { 1495 name: string 1496 age: number 1497 isVis: boolean 1498 1499 constructor(name: string, age: number, isVis: boolean) { 1500 this.name = name 1501 this.age = age 1502 this.isVis = isVis 1503 } 1504} 1505 1506let source: SourceObject = new SourceObject("jack", 18, false); 1507let g_object: distributedDataObject.DistributedObject = distributedDataObject.createDistributedObject(source); 1508// Unregister the specified status change callback. 1509g_object.off("status", (sessionId: string, networkId: string, status: 'online' | 'offline') => { 1510 console.info("status changed " + sessionId + " " + status + " " + networkId); 1511}); 1512// Unregister all status change callbacks. 1513g_object.off("status"); 1514``` 1515