Bug 1824856 - add release-notify-testrail to treeherder. r=gbrown,releng-reviewers...
[gecko.git] / mobile / android / docs / rfcs / 0012-introduce-ui-store.md
blob22416f6184b0aef86c824abccb23b295f4bf431b
1 ---
2 layout: page
3 title: Introduce a Store for UI components
4 permalink: /rfc/0012-introduce-ui-store
5 ---
7 * Start date: 2024-01-29
8 * RFC PR: [#5353](https://github.com/mozilla-mobile/firefox-android/pull/5353)
10 ## Summary
12 In most applications of the `Store`, it is preferable to have reducers perform work on the main thread. Having actions reduced immediately at the point of dispatch, simplifies the reasoning a developer would need to go through for most UI-based work that happens on the main thread.
14 ## Motivation
16 Android embedders use the main thread for UI, user-facing, or gesture handling work. For example, notifying UI components when IO from storage layers have completed, an engine's task that can happen on a separate thread, or global-level state updates for different components to observe.
18 When components dispatch actions, they are performed on an independant single thread dispatcher in the `Store` to avoid overloading the main thread with heavy work that might be performed during the `reduce` or in a `Middleware`. In practice, these actions have been short and fast so they do not cause overhead (most of these actions have been [data class copying][0]).  In addition, side-effects done in a `Middleware` which can be slow, like I/O,  are put onto separate Dispatchers. The performance optimization to switch to a `Store` thread, requires that components which are always run on the main thread, to ensure synchronisation is now kept between the main thread and the store thread for observers of the `State`.
20 There are some advantages to this change:
22 * Simplicity for `Store`s that are meant for UI facing work.
23 * Unit testing can now occur on the test framework's thread.
24 * Fewer resources needed for context shifting between threads[^1].
26 For an example of thread simplicity, an `Engine` typically has its own 'engine thread' to perform async work and post/request results to the main thread (these APIs are identified with the `@UiThread` annotation). Once we get the callback for those results, we then need to dispatch an action to the store that will then happen on a `Store` thread. Feature components then observe for state changes and then make UI changes on the main thread. A simplified form of this thread context switching can be seen in the example below:
28 ```kotlin
29 // engine thread
30 engineView.requestApiResult { result ->
31   // received on the main thread.
32   store.dispatch(UpdateResultAction(result))
35 // store thread
36 fun reduce(state: State, action: Action) {
37   is UpdateResultAction -> {
38     // do things here.
39   }
42 // store thread
43 Middleware {
44   override fun invoke(
45     context: MiddlewareContext<State, Action>,
46     next: (Action) -> Unit,
47     action: Action,
48   ) {
49     // perform side-effects that also happen on the store thread.
50   }
53 // main thread
54 store.flowScoped { flow ->
55   flow.collect {
56     // perform work on the main thread.
57   }
59 ```
61 With the changes in this RFC, this switching of threads can be reduced (notable comments marked with 📝):
63 ```kotlin
64 // engine thread
65 engineView.requestApiResult { result ->
66   // received on the main thread.
67   store.dispatch(UpdateResultAction(result))
70 // 📝 main thread - now on the same thread, processed immediately.
71 fun reduce(state: State, action: Action) {
72   is UpdateResultAction -> {
73     // do things here.
74   }
77 // 📝 main thread - now on the same thread, processed immediately.
78 Middleware {
79   override fun invoke(
80     context: MiddlewareContext<State, Action>,
81     next: (Action) -> Unit,
82     action: Action,
83   ) {
84     // 📝 perform side-effects that now happen on the main thread.
85   }
88 // main thread
89 store.flowScoped { flow ->
90   flow.collect {
91       // perform work on the main thread.
92     }
93   }
95 ```
97 Additionally, from [performance investigations already done][2], we know that Fenix creates over a hundred threads within a few seconds of startup. Reducing the number of threads for Stores that do not have a strong requirement to run on a separate thread will lower the applications memory footprint.
99 ## Guide-level explanation
101 Extending the existing `Store` class to use the `Dispatchers.Main.immediate` will ensure that UI stores will stay on the same UI thread and have that work done immediately. Using a distinct class named `UiStore` also makes it clear to the developer that this is work that will be done on the UI thread and its implications will be made a bit more clear when it's used.
103 ```kotlin
104 @MainThread
105 open class UiStore<S : State, A : Action>(
106   initialState: S,
107   reducer: Reducer<S, A>,
108   middleware: List<Middleware<S, A>> = emptyList(),
109 ) : Store<S, A>(
110   initialState,
111   reducer,
112   middleware,
113   UiStoreDispatcher(),
116 open class Store<S : State, A : Action> internal constructor(
117   initialState: S,
118   reducer: Reducer<S, A>,
119   middleware: List<Middleware<S, A>>,
120   dispatcher: StoreDispatcher,
121 ) {
122   constructor(
123     initialState: S,
124     reducer: Reducer<S, A>,
125     middleware: List<Middleware<S, A>> = emptyList(),
126     threadNamePrefix: String? = null,
127   ) : this(
128     initialState = initialState,
129     reducer = reducer,
130     middleware = middleware,
131     dispatcher = DefaultStoreDispatcher(threadNamePrefix),
132   )
135 interface StoreDispatcher {
136   val dispatcher: CoroutineDispatcher
137   val scope: CoroutineScope
138   val coroutineContext: CoroutineContext
140   // Each Store has it's own `assertOnThread` because in the Thread owner is different in both context.
141   fun assertOnThread()
145 Applications can use this similar to any other store then. An "AppStore" example below can switch :
147 ```kotlin
148 // changing the one line below from `UiStore` to `Store` gives the developer the ability to switch existing Stores between the different Store types.
149 class AppStore(
150   initialState: AppState = AppState(),
151 ) : UiStore<AppState, AppAction>(
152   initialState = initialState,
153   reducer = AppStoreReducer::reduce,
157 ## Drawbacks
159 * Mistakenly doing work on the main thread - we could end up performing large amounts of work on the main thread unintentionally if we are not careful. This could be because of a large number of small tasks, a single large task, a blocking task, or a combination. As the developer is choosing to use a `UiStore`, they will be expected to ensure that heavy work they do, as is with mobile UI development done today, is not done on the main thread.
161 ## Rationale and alternatives
163 Not introducing this new Store type would not change current development where the developer needs to ensure understanding that dispatched actions will be processed at a later time.
165 ## Future work
167 We have opportunities to iterate from here and consider if/how we want to pass a CoroutineScope in. This can be part of future RFC proposals however.
169 ## Unresolved questions
171 * While performance gains are not an explicit intent, there is a theoretical advantage, but not one we will pursue as part of this RFC. How much would we save, if any?
172 * Some additional changes need to be done to allow the `Store` to override the default `StoreThreadFactory` that will allow assertions against a thread (`MainThread`) not created by the `StoreThreadFactory` itself. This should be possible, but will this add to additional complexity?
174 [0]: https://kotlinlang.org/docs/data-classes.html#copying
175 [^1]: https://github.com/mozilla-mobile/android-components/issues/9424
176 [2]: https://github.com/mozilla-mobile/android-components/issues/9424#issue-787013588