• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Data Synchronization Between UIAbility and UI Page
2
3
4Based on the application model, you can use any of the following ways to implement data synchronization between [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) components and UI pages:
5
6- [Using EventHub for Data Synchronization](#using-eventhub-for-data-synchronization): The [EventHub](../reference/apis-ability-kit/js-apis-inner-application-eventHub.md) object is provided by the [base class Context](../reference/apis-ability-kit/js-apis-inner-application-context.md). It allows events to be transferred using the publish/subscribe (pub/sub) pattern. Specifically, after subscribing to an event, your application will receive the event and process it accordingly when the event is published.
7- [Using AppStorage or LocalStorage for Data Synchronization](#using-appstorage-or-localstorage-for-data-synchronization): ArkUI provides two application-level state management solutions: [AppStorage](../ui/state-management/arkts-appstorage.md) and [LocalStorage](../ui/state-management/arkts-localstorage.md), which implement application- and UIAbility-level data synchronization, respectively.
8
9
10## Using EventHub for Data Synchronization
11
12[EventHub](../reference/apis-ability-kit/js-apis-inner-application-eventHub.md) provides an event mechanism for the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) component so that they can subscribe to, unsubscribe from, and trigger events.
13
14In the [base class Context](../reference/apis-ability-kit/js-apis-inner-application-context.md), the EventHub object is provided for communication within the UIAbility component instance. Before using EventHub to implement data communication between the UIAbility and UI, you must obtain an EventHub object. This section uses EventHub as an example.
15
161. Call [eventHub.on()](../reference/apis-ability-kit/js-apis-inner-application-eventHub.md#eventhubon) in the UIAbility in either of the following ways to register a custom event **event1**.
17
18    ```ts
19    import { hilog } from '@kit.PerformanceAnalysisKit';
20    import { UIAbility, Context, Want, AbilityConstant } from '@kit.AbilityKit';
21
22    const DOMAIN_NUMBER: number = 0xFF00;
23    const TAG: string = '[EventAbility]';
24
25    export default class EntryAbility extends UIAbility {
26      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
27        // Obtain an eventHub object.
28        let eventhub = this.context.eventHub;
29        // Subscribe to the event.
30        eventhub.on('event1', this.eventFunc);
31        eventhub.on('event1', (data: string) => {
32          // Trigger the event to complete the service operation.
33        });
34        hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onCreate');
35      }
36
37      // ...
38      eventFunc(argOne: Context, argTwo: Context): void {
39        hilog.info(DOMAIN_NUMBER, TAG, '1. ' + `${argOne}, ${argTwo}`);
40        return;
41      }
42    }
43    ```
44
452. Call [eventHub.emit()](../reference/apis-ability-kit/js-apis-inner-application-eventHub.md#eventhubemit) on the UI page to trigger the event, and pass in the parameters as required.
46
47    ```ts
48    import { common } from '@kit.AbilityKit';
49
50    @Entry
51    @Component
52    struct Page_EventHub {
53      private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
54
55      eventHubFunc(): void {
56        // Trigger the event without parameters.
57        this.context.eventHub.emit('event1');
58        // Trigger the event with one parameter.
59        this.context.eventHub.emit('event1', 1);
60        // Trigger the event with two parameters.
61        this.context.eventHub.emit('event1', 2, 'test');
62        // You can design the parameters based on your service requirements.
63      }
64
65      build() {
66        Column() {
67          // ...
68          List({ initialIndex: 0 }) {
69            ListItem() {
70              Row() {
71                // ...
72              }
73              .onClick(() => {
74                this.eventHubFunc();
75                this.getUIContext().getPromptAction().showToast({
76                  message: 'EventHubFuncA'
77                });
78              })
79            }
80
81            // ...
82            ListItem() {
83              Row() {
84                // ...
85              }
86              .onClick(() => {
87                this.context.eventHub.off('event1');
88                this.getUIContext().getPromptAction().showToast({
89                  message: 'EventHubFuncB'
90                });
91              })
92            }
93            // ...
94          }
95          // ...
96        }
97        // ...
98      }
99    }
100    ```
101
1023. Obtain the event trigger result from the subscription callback of the UIAbility. The run log result is as follows:
103
104    ```json
105    [Example].[Entry].[EntryAbility] 1. []
106    [Example].[Entry].[EntryAbility] 1. [1]
107    [Example].[Entry].[EntryAbility] 1. [2,"test"]
108    ```
109
1104. When **event1** is not needed, call [eventHub.off()](../reference/apis-ability-kit/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event.
111
112    ```ts
113    import { UIAbility } from '@kit.AbilityKit';
114
115    export default class EntryAbility extends UIAbility {
116      // ...
117      onDestroy(): void {
118        this.context.eventHub.off('event1');
119      }
120    }
121    ```
122
123## Using AppStorage or LocalStorage for Data Synchronization
124
125ArkUI provides two application-level state management solutions: [AppStorage](../ui/state-management/arkts-appstorage.md) and [LocalStorage](../ui/state-management/arkts-localstorage.md), which implement data synchronization at the application or [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) level, respectively. Both solutions can be used to manage the application state, enhance application performance, and improve user experience. The AppStorage is a global state manager that manages state data shared among multiple UIAbility components. The LocalStorage is a local state manager that manages state data used inside a single UIAbility. They help you control the application state more flexibly and improve the maintainability and scalability of applications. For details, see [State Management of Application-Level Variables](../ui/state-management/arkts-application-state-management-overview.md).
126