-
Notifications
You must be signed in to change notification settings - Fork 901
/
Router.kt
278 lines (249 loc) · 8.33 KB
/
Router.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/*
* Copyright (C) 2017. Uber Technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.uber.rib.core
import android.os.Looper
import androidx.annotation.CallSuper
import androidx.annotation.MainThread
import androidx.annotation.VisibleForTesting
import com.uber.rib.core.RibEvents.triggerRibActionAndEmitEvents
import com.uber.rib.core.internal.CoreFriendModuleApi
import java.util.Locale
import java.util.concurrent.CopyOnWriteArrayList
/**
* Responsible for handling the addition and removal of children routers.
*
* @param <I> type of interactor this router routes.
*/
public abstract class Router<I : InteractorType>
protected constructor(
component: InteractorBaseComponent<*>?,
public open val interactor: I,
private val ribRefWatcher: RibRefWatcher,
private val mainThread: Thread,
) : RibActionEmitter {
private val children: MutableList<Router<*>> = CopyOnWriteArrayList()
private val interactorGeneric: Interactor<*, *>
get() = interactor as Interactor<*, *>
/** @return the Tag. */
@CoreFriendModuleApi
public var tag: String? = null
private set
private var savedInstanceState: Bundle? = null
private var isLoaded = false
protected constructor(
interactor: I,
component: InteractorBaseComponent<*>?,
) : this(component, interactor, RibRefWatcher.getInstance(), getMainThread())
protected constructor(
interactor: I,
) : this(null, interactor, RibRefWatcher.getInstance(), getMainThread())
@Suppress("UNCHECKED_CAST")
protected fun inject(component: InteractorBaseComponent<*>?) {
(component as? InteractorBaseComponent<Interactor<*, *>>)?.inject(interactorGeneric)
}
@OptIn(CoreFriendModuleApi::class)
protected open fun attachToInteractor() {
interactorGeneric.setRouterInternal(this)
}
/**
* Dispatch back press to the associated interactor. Do not override this.
*
* @return TRUE if the interactor handles the back press.
*/
public open fun handleBackPress(): Boolean {
ribRefWatcher.logBreadcrumb("BACKPRESS", null, null)
return interactorGeneric.handleBackPress()
}
/** Called after the router has been loaded and initialized. */
@Initializer protected open fun didLoad() {}
/**
* Called when a router is being attached. Router subclasses can perform setup here for anything
* that is needed again but is cleaned up in willDetach(). Use didLoad() if the setup is only
* needed once.
*/
protected open fun willAttach() {}
/**
* Called when a router is being a detached, router subclasses should perform any required clean
* up here.
*/
protected open fun willDetach() {}
@MainThread
public open fun attachChild(childRouter: Router<*>) {
attachChild(childRouter, childRouter.javaClass.name)
}
/**
* Attaches a child router to this router.
*
* @param childRouter the [Router] to be attached.
* @param tag an identifier to namespace saved instance state [Bundle] objects.
*/
@OptIn(CoreFriendModuleApi::class)
@MainThread
public open fun attachChild(childRouter: Router<*>, tag: String) {
for (child in children) {
if (tag == child.tag) {
Rib.getConfiguration()
.handleNonFatalWarning(
String.format(
Locale.getDefault(),
"There is already a child router with tag: %s",
tag,
),
null,
)
}
}
triggerRibActionAndEmitEvents(
childRouter,
RibActionEmitterType.ROUTER,
RibEventType.ATTACHED,
) {
children.add(childRouter)
}
ribRefWatcher.logBreadcrumb(
"ATTACHED",
childRouter.javaClass.simpleName,
this.javaClass.simpleName,
)
RibEvents.emitRouterEvent(RibEventType.ATTACHED, childRouter, this)
var childBundle: Bundle? = null
if (savedInstanceState != null) {
val previousChildren = savedInstanceState?.getBundleExtra(KEY_CHILD_ROUTERS)
childBundle = previousChildren?.getBundleExtra(tag)
}
childRouter.dispatchAttach(childBundle, tag)
}
/**
* Detaches the {@param childFactory} from the current [Interactor]. NOTE: No consumers of this
* API should ever keep a reference to the detached child router, leak canary will enforce that it
* gets garbage collected.
*
* If you need to keep references to previous routers, use RouterNavigator.
*
* @param childRouter the [Router] to be detached.
*/
@OptIn(CoreFriendModuleApi::class)
@MainThread
public open fun detachChild(childRouter: Router<*>) {
val isChildRemoved = children.remove(childRouter)
val interactor = childRouter.interactor
ribRefWatcher.watchDeletedObject(interactor)
ribRefWatcher.logBreadcrumb(
"DETACHED",
childRouter.javaClass.simpleName,
this.javaClass.simpleName,
)
if (savedInstanceState != null) {
val childrenBundles = savedInstanceState?.getBundleExtra(KEY_CHILD_ROUTERS)
val childRouterTag = childRouter.tag
if (childRouterTag != null) {
childrenBundles?.putBundleExtra(childRouterTag, null)
} else {
Rib.getConfiguration()
.handleNonFatalWarning("A RIB tried to detach a child that was never attached", null)
}
}
triggerRibActionAndEmitEvents(
childRouter,
RibActionEmitterType.ROUTER,
RibEventType.DETACHED,
) {
childRouter.dispatchDetach()
}
if (isChildRemoved) {
RibEvents.emitRouterEvent(RibEventType.DETACHED, childRouter, this)
}
}
@CallSuper
public open fun dispatchAttach(savedInstanceState: Bundle?) {
dispatchAttach(savedInstanceState, javaClass.name)
}
@OptIn(CoreFriendModuleApi::class)
@CallSuper
@Initializer
public open fun dispatchAttach(savedInstanceState: Bundle?, tag: String) {
checkForMainThread()
if (!isLoaded) {
isLoaded = true
didLoad()
}
this.savedInstanceState = savedInstanceState
this.tag = tag
willAttach()
var interactorBundle: Bundle? = null
if (this.savedInstanceState != null) {
interactorBundle = this.savedInstanceState!!.getBundleExtra(KEY_INTERACTOR)
}
interactorGeneric.dispatchAttach(interactorBundle)
}
public open fun dispatchDetach() {
checkForMainThread()
interactorGeneric.dispatchDetach()
willDetach()
for (child in children) {
detachChild(child)
}
}
/**
* Gets the children of this [Router].
*
* @return Children.
*/
@CoreFriendModuleApi
public open fun getChildren(): List<Router<*>> {
return children
}
@CoreFriendModuleApi
public fun saveInstanceStateInternal(outState: Bundle) {
saveInstanceState(outState)
}
@OptIn(CoreFriendModuleApi::class)
protected open fun saveInstanceState(outState: Bundle) {
val interactorSavedInstanceState = Bundle()
interactorGeneric.onSaveInstanceStateInternal(interactorSavedInstanceState)
outState.putBundleExtra(KEY_INTERACTOR, interactorSavedInstanceState)
val childBundles = Bundle()
for (child in children) {
val childBundle = Bundle()
child.saveInstanceState(childBundle)
childBundles.putBundleExtra(child.tag!!, childBundle)
}
outState.putBundleExtra(KEY_CHILD_ROUTERS, childBundles)
}
private fun checkForMainThread() {
if (mainThread !== Thread.currentThread()) {
val errorMessage = "Call must happen on the main thread"
val exception = IllegalStateException(errorMessage)
Rib.getConfiguration().handleNonFatalError(errorMessage, exception)
}
}
public companion object {
@VisibleForTesting public val KEY_CHILD_ROUTERS: String = "Router.childRouters"
@JvmField @VisibleForTesting public val KEY_INTERACTOR: String = "Router.interactor"
@JvmStatic
public fun getMainThread(): Thread {
return try {
Looper.getMainLooper().thread
} catch (e: Exception) {
Thread.currentThread()
}
}
}
init {
inject(component)
attachToInteractor()
}
}