• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# AppStorage: Application-wide UI State Storage
2
3
4AppStorage provides the central storage for mutable application UI state attributes. It is bound to the application process and is created by the UI framework at application startup.
5
6
7Unlike LocalStorage, which is usually used for page-level state sharing, AppStorage enables application-wide UI state sharing. AppStorage is equivalent to the hub of the entire application. [PersistentStorage](arkts-persiststorage.md) and [Environment](arkts-environment.md) data is passed first to AppStorage and then from AppStorage to the UI component.
8
9
10This topic describes only the AppStorage application scenarios and related decorators: \@StorageProp and \@StorageLink.
11
12
13## Overview
14
15AppStorage is a singleton object that is created at application startup. Its purpose is to provide the central storage for mutable application UI state attributes. AppStorage retains all those attributes and their values as long as the application remains running. Attributes are accessed using a unique key string value.
16
17UI components synchronize application state attributes with the AppStorage. Implementation of application business logic can access AppStorage as well.
18
19Selected state attributes of AppStorage can be synced with different data sources or data sinks. Those data sources and sinks can be on a local or remote device, and have different capabilities, such as data persistence (see [PersistentStorage](arkts-persiststorage.md)). These data sources and sinks are implemented in the business logic, separate from the UI. Link those AppStorage attributes to [@StorageProp](#storageprop) and [@StorageLink](#storagelink) whose values should be kept until application re-start.
20
21
22## \@StorageProp
23
24As mentioned above, if you want to establish a binding between AppStorage and a custom component, you'll need the \@StorageProp and \@StorageLink decorators. Use \@StorageProp(key) or \@StorageLink(key) to decorate variables in the component, where **key** identifies the attribute in AppStorage.
25
26When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Local initialization is mandatory. If an attribute with the given key is missing from AppStorage, it will be added with the stated initializing value. (Whether the attribute with the given key exists in AppStorage depends on the application logic.)
27
28
29By decorating a variable with \@StorageProp(key), a one-way data synchronization is established with the attribute with the given key in AppStorage. A local change can be made, but it will not be synchronized to AppStorage. An update to the attribute with the given key in AppStorage will overwrite local changes.
30
31
32### Rules of Use
33
34| \@StorageProp Decorator| Description                                      |
35| ------------------ | ---------------------------------------- |
36| Decorator parameters             | **key**: constant string, mandatory (note, the string is quoted)                 |
37| Allowed variable types         | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified and must be the same as the corresponding attribute in LocalStorage. **any** is not supported. The **undefined** and **null** values are not allowed.|
38| Synchronization type              | One-way: from the attribute in AppStorage to the component variable.<br>The component variable can be changed locally, but an update from AppStorage will overwrite local changes.|
39| Initial value for the decorated variable         | Mandatory. It is used as the default value for initialization if the attribute does not exist in AppStorage.|
40
41
42### Variable Transfer/Access Rules
43
44| Transfer/Access     | Description                                      |
45| ---------- | ---------------------------------------- |
46| Initialization and update from the parent component| Forbidden.|
47| Subnode initialization    | Supported; can be used to initialize an \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.|
48| Access | None.                                      |
49
50
51  **Figure 1** \@StorageProp initialization rule
52
53
54![en-us_image_0000001552978157](figures/en-us_image_0000001552978157.png)
55
56
57### Observed Changes and Behavior
58
59**Observed Changes**
60
61
62- When the decorated variable is of the Boolean, string, or number type, its value change can be observed.
63
64- When the decorated variable is of the class or Object type, its value change and value changes of all its attributes, that is, the attributes that **Object.keys(observedObject)** returns.
65
66- When the decorated variable is of the array type, the addition, deletion, and updates of array items can be observed.
67
68
69**Framework Behavior**
70
71
72- When the value change of the \@StorageProp(key) decorated variable is observed, the change is not synchronized to the attribute with the give key value in AppStorage.
73
74- The value change of the \@StorageProp(key) decorated variable only applies to the private member variables of the current component, but not other variables bound to the key.
75
76- When the data decorated by \@StorageProp(key) is a state variable, the change of the data is not synchronized to AppStorage, but the owning custom component is re-rendered.
77
78- When the attribute with the given key in AppStorage is updated, the change is synchronized to all the \@StorageProp(key) decorated data, and the local changes of the data are overwritten.
79
80
81## \@StorageLink
82
83\@StorageLink(key) creates a two-way data synchronization with the attribute with the given key in AppStorage.
84
851. If a local change occurs, it is synchronized to AppStorage.
86
872. Changes in AppStorage are synchronized to all attributes with the given key, including one-way bound variables (\@StorageProp decorated variables and one-way bound variables created through \@Prop), two-way bound variables (\@StorageLink decorated variables and two-way bound variables created through \@Link), and other instances (such as PersistentStorage).
88
89
90### Rules of Use
91
92| \@StorageLink Decorator| Description                                      |
93| ------------------ | ---------------------------------------- |
94| Decorator parameters             | **key**: constant string, mandatory (note, the string is quoted)                 |
95| Allowed variable types         | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified and must be the same as the corresponding attribute in AppStorage. **any** is not supported. The **undefined** and **null** values are not allowed.|
96| Synchronization type              | Two-way: from the attribute in AppStorage to the custom component variable and back|
97| Initial value for the decorated variable         | Mandatory. It is used as the default value for initialization if the attribute does not exist in AppStorage.|
98
99
100### Variable Transfer/Access Rules
101
102| Transfer/Access     | Description                                      |
103| ---------- | ---------------------------------------- |
104| Initialization and update from the parent component| Forbidden.                                     |
105| Subnode initialization    | Supported; can be used to initialize a regular variable or \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.|
106| Access | None.                                      |
107
108
109  **Figure 2** \@StorageLink initialization rule
110
111
112![en-us_image_0000001501938718](figures/en-us_image_0000001501938718.png)
113
114
115### Observed Changes and Behavior
116
117**Observed Changes**
118
119
120- When the decorated variable is of the Boolean, string, or number type, its value change can be observed.
121
122- When the decorated variable is of the class or Object type, its value change and value changes of all its attributes, that is, the attributes that **Object.keys(observedObject)** returns.
123
124- When the decorated variable is of the array type, the addition, deletion, and updates of array items can be observed.
125
126
127**Framework Behavior**
128
129
1301. When the value change of the \@StorageLink(key) decorated variable is observed, the change is synchronized to the attribute with the give key value in AppStorage.
131
1322. Once the attribute with the given key in AppStorage is updated, all the data (including \@StorageLink and \@StorageProp decorated variables) bound to the attribute key is changed synchronously.
133
1343. When the data decorated by \@StorageLink(key) is a state variable, the change of the data is synchronized to AppStorage, and the owning custom component is re-rendered.
135
136
137## Application Scenarios
138
139
140### Example of Using AppStorage and LocalStorage from Application Logic
141
142Since AppStorage is a singleton, its APIs are all static ones. How these APIs work resembles the non-static APIs of LocalStorage.
143
144
145```ts
146AppStorage.SetOrCreate('PropA', 47);
147
148let storage: LocalStorage = new LocalStorage({ 'PropA': 17 });
149let propA: number = AppStorage.Get('PropA') // propA in AppStorage == 47, propA in LocalStorage == 17
150var link1: SubscribedAbstractProperty<number> = AppStorage.Link('PropA'); // link1.get() == 47
151var link2: SubscribedAbstractProperty<number> = AppStorage.Link('PropA'); // link2.get() == 47
152var prop: SubscribedAbstractProperty<number> = AppStorage.Prop('PropA'); // prop.get() = 47
153
154link1.set(48); // two-way sync: link1.get() == link2.get() == prop.get() == 48
155prop.set(1); // one-way sync: prop.get()=1; but link1.get() == link2.get() == 48
156link1.set(49); // two-way sync: link1.get() == link2.get() == prop.get() == 49
157
158storage.get('PropA') // == 17
159storage.set('PropA', 101);
160storage.get('PropA') // == 101
161
162AppStorage.Get('PropA') // == 49
163link1.get() // == 49
164link2.get() // == 49
165prop.get() // == 49
166```
167
168
169### Example of Using AppStorage and LocalStorage from Inside the UI
170
171\@StorageLink works together with the AppStorage in the same way as \@LocalStorageLink works together with LocalStorage. It creates two-way data synchronization with an attribute in AppStorage.
172
173
174```ts
175AppStorage.SetOrCreate('PropA', 47);
176let storage = new LocalStorage({ 'PropA': 48 });
177
178@Entry(storage)
179@Component
180struct CompA {
181  @StorageLink('PropA') storLink: number = 1;
182  @LocalStorageLink('PropA') localStorLink: number = 1;
183
184  build() {
185    Column({ space: 20 }) {
186      Text(`From AppStorage ${this.storLink}`)
187        .onClick(() => this.storLink += 1)
188
189      Text(`From LocalStorage ${this.localStorLink}`)
190        .onClick(() => this.localStorLink += 1)
191    }
192  }
193}
194```
195
196### Persistent Subscription and Callback
197
198The persistent subscription and callback can help reduce overhead and enhance code readability.
199
200
201```ts
202// xxx.ets
203import emitter from '@ohos.events.emitter';
204
205let NextID: number = 0;
206
207class ViewData {
208  title: string;
209  uri: Resource;
210  color: Color = Color.Black;
211  id: number;
212
213  constructor(title: string, uri: Resource) {
214    this.title = title;
215    this.uri = uri
216    this.id = NextID++;
217  }
218}
219
220@Entry
221@Component
222struct Gallery2 {
223  dataList: Array<ViewData> = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))]
224  scroller: Scroller = new Scroller()
225  private preIndex: number = -1
226
227  build() {
228    Column() {
229      Grid(this.scroller) {
230        ForEach(this.dataList, (item: ViewData) => {
231          GridItem() {
232            TapImage({
233              uri: item.uri,
234              index: item.id
235            })
236          }.aspectRatio(1)
237          .onClick(() => {
238            if (this.preIndex === item.id) {
239              return
240            }
241            var innerEvent = { eventId: item.id }
242            // Selected: from black to red
243            var eventData = {
244              data: {
245                "colorTag": 1
246              }
247            }
248            emitter.emit(innerEvent, eventData)
249
250            if (this.preIndex != -1) {
251              console.info(`preIndex: ${this.preIndex}, index: ${item.id}, black`)
252              var innerEvent = { eventId: this.preIndex }
253              // Deselected: from red to black
254              var eventData = {
255                data: {
256                  "colorTag": 0
257                }
258              }
259              emitter.emit(innerEvent, eventData)
260            }
261            this.preIndex = item.id
262          })
263
264        }, (item: ViewData) => JSON.stringify(item))
265      }.columnsTemplate('1fr 1fr')
266    }
267
268  }
269}
270
271@Component
272export struct TapImage {
273  @State tapColor: Color = Color.Black;
274  private index: number;
275  private uri: Resource;
276
277  onTapIndexChange(colorTag: emitter.EventData) {
278    this.tapColor = colorTag.data.colorTag ? Color.Red : Color.Black
279  }
280
281  aboutToAppear() {
282    // Define the event ID.
283    var innerEvent = { eventId: this.index }
284    emitter.on(innerEvent, this.onTapIndexChange.bind(this))
285  }
286
287  build() {
288    Column() {
289      Image(this.uri)
290        .objectFit(ImageFit.Cover)
291        .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor })
292    }
293  }
294}
295```
296
297The following example uses the message mechanism to subscribe to events. Because this mechanism can result in a large number of nodes to listen for and a long implementation time, it is not recommended.
298
299
300```ts
301// xxx.ets
302class ViewData {
303  title: string;
304  uri: Resource;
305  color: Color = Color.Black;
306
307  constructor(title: string, uri: Resource) {
308    this.title = title;
309    this.uri = uri
310  }
311}
312
313@Entry
314@Component
315struct Gallery2 {
316  dataList: Array<ViewData> = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))]
317  scroller: Scroller = new Scroller()
318
319  build() {
320    Column() {
321      Grid(this.scroller) {
322        ForEach(this.dataList, (item: ViewData, index?: number) => {
323          GridItem() {
324            TapImage({
325              uri: item.uri,
326              index: index
327            })
328          }.aspectRatio(1)
329
330        }, (item: ViewData, index?: number) => {
331          return JSON.stringify(item) + index;
332        })
333      }.columnsTemplate('1fr 1fr')
334    }
335
336  }
337}
338
339@Component
340export struct TapImage {
341  @StorageLink('tapIndex') @Watch('onTapIndexChange') tapIndex: number = -1;
342  @State tapColor: Color = Color.Black;
343  private index: number;
344  private uri: Resource;
345
346  // Check whether the component is selected.
347  onTapIndexChange() {
348    if (this.tapIndex >= 0 && this.index === this.tapIndex) {
349      console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, red`)
350      this.tapColor = Color.Red;
351    } else {
352      console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, black`)
353      this.tapColor = Color.Black;
354    }
355  }
356
357  build() {
358    Column() {
359      Image(this.uri)
360        .objectFit(ImageFit.Cover)
361        .onClick(() => {
362          this.tapIndex = this.index;
363        })
364        .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor })
365    }
366
367  }
368}
369```
370
371
372## Restrictions
373
374When using AppStorage together with [PersistentStorage](arkts-persiststorage.md) and [Environment](arkts-environment.md), pay attention to the following:
375
376- A call to **PersistentStorage.PersistProp()** after creating the attribute in AppStorage uses the type and value in AppStorage and overwrites any attribute with the same name in PersistentStorage. In light of this, the opposite order of calls is recommended. For an example of incorrect usage, see [Accessing Attribute in AppStorage Before PersistentStorage](arkts-persiststorage.md#accessing-attribute-in-appstorage-before-persistentstorage).
377
378- A call to **Environment.EnvProp()** after creating the attribute in AppStorage will fail. This is because AppStorage already has an attribute with the same name, and the environment variable will not be written into AppStorage. Therefore, you are advised not to use the preset environment variable name in AppStorage.
379
380- Changes to the variables decorated by state decorators will cause UI re-render. If the changes are for message communication, rather than for UI re-render, the emitter mode is recommended. For the example, see [Persistent Subscription and Callback](#persistent-subscription-and-callback).
381<!--no_check-->
382