-
Notifications
You must be signed in to change notification settings - Fork 17
/
ModoScreenAndroidAdapter.kt
281 lines (249 loc) · 10.3 KB
/
ModoScreenAndroidAdapter.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
279
280
281
package com.github.terrakok.modo.android
import android.app.Application
import android.content.Context
import android.os.Bundle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocal
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.ProvidedValue
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.LocalSavedStateRegistryOwner
import androidx.lifecycle.HasDefaultViewModelProviderFactory
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.SAVED_STATE_REGISTRY_OWNER_KEY
import androidx.lifecycle.SavedStateViewModelFactory
import androidx.lifecycle.VIEW_MODEL_STORE_OWNER_KEY
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.enableSavedStateHandles
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.MutableCreationExtras
import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner
import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryController
import androidx.savedstate.SavedStateRegistryOwner
import com.github.terrakok.modo.Screen
import com.github.terrakok.modo.model.ScreenModelStore
import com.github.terrakok.modo.util.getActivity
import com.github.terrakok.modo.util.getApplication
import java.util.concurrent.atomic.AtomicReference
/**
* Adapter to link modo with android. It the single instance of [ModoScreenAndroidAdapter] per Screen.
*/
class ModoScreenAndroidAdapter private constructor(
// just for debug purpose.
// internal val screen: Screen
) :
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
HasDefaultViewModelProviderFactory {
override val lifecycle: LifecycleRegistry = LifecycleRegistry(this)
override val viewModelStore: ViewModelStore = ViewModelStore()
override val savedStateRegistry: SavedStateRegistry
get() = controller.savedStateRegistry
override val defaultViewModelProviderFactory: ViewModelProvider.Factory
get() = SavedStateViewModelFactory(
application = atomicContext.get()?.applicationContext?.getApplication(),
owner = this
)
override val defaultViewModelCreationExtras: CreationExtras
get() = MutableCreationExtras().apply {
application?.let {
set(ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY, it)
}
set(SAVED_STATE_REGISTRY_OWNER_KEY, this@ModoScreenAndroidAdapter)
set(VIEW_MODEL_STORE_OWNER_KEY, this@ModoScreenAndroidAdapter)
/* TODO if (getArguments() != null) {
extras.set<Bundle>(DEFAULT_ARGS_KEY, getArguments())
}*/
}
private val controller = SavedStateRegistryController.create(this)
private var isCreated: Boolean by mutableStateOf(false)
// Atomic references for cases when we unable take it directly from the composition.
private val atomicContext = AtomicReference<Context>()
private val atomicParentLifecycleOwner = AtomicReference<LifecycleOwner>()
private val application: Application? get() = atomicContext.get()?.applicationContext?.getApplication()
init {
controller.performAttach()
enableSavedStateHandles()
}
private fun onCreate(savedState: Bundle?) {
check(!isCreated) { "onCreate already called" }
isCreated = true
controller.performRestore(savedState)
initEvents.forEach {
lifecycle.safeHandleLifecycleEvent(it)
}
}
private fun emitOnStartEvents() {
startEvents.forEach {
lifecycle.safeHandleLifecycleEvent(it)
}
}
private fun emitOnStopEvents() {
stopEvents.forEach {
lifecycle.safeHandleLifecycleEvent(it)
}
}
@Composable
fun ProvideAndroidIntegration(
content: @Composable () -> Unit
) {
val context: Context = LocalContext.current
val parentLifecycleOwner = LocalLifecycleOwner.current
LifecycleDisposableEffect(context, parentLifecycleOwner)
@Suppress("SpreadOperator")
CompositionLocalProvider(*getProviders()) {
content()
}
}
@Suppress("UnusedParameter")
fun onDispose(screen: Screen) {
viewModelStore.clear()
disposeEvents.forEach { event ->
lifecycle.safeHandleLifecycleEvent(event)
}
}
private fun performSave(outState: Bundle) {
controller.performSave(outState)
}
@Composable
private fun getProviders(): Array<ProvidedValue<*>> {
DisposableAtomicReference(LocalContext, atomicContext)
DisposableAtomicReference(LocalLifecycleOwner, atomicParentLifecycleOwner)
return remember(this) {
arrayOf(
LocalLifecycleOwner provides this,
LocalViewModelStoreOwner provides this,
LocalSavedStateRegistryOwner provides this
)
}
}
/**
* Capture value from [compositionLocal] to [atomicReference] when it enters the composition and clears it when lives or new value is provided.
*/
@Composable
private fun <T> DisposableAtomicReference(compositionLocal: CompositionLocal<T>, atomicReference: AtomicReference<T>) {
val value = compositionLocal.current
DisposableEffect(value) {
atomicReference.compareAndSet(null, value)
onDispose {
atomicReference.set(null)
}
}
}
/**
* Returns a unregister callback
*/
private fun registerParentLifecycleListener(
lifecycleOwner: LifecycleOwner?,
observerFactory: () -> LifecycleObserver
): () -> Unit {
if (lifecycleOwner != null) {
val parentLifecycleObserver = observerFactory()
val lifecycle = lifecycleOwner.lifecycle
lifecycle.addObserver(parentLifecycleObserver)
return {
lifecycle.removeObserver(parentLifecycleObserver)
}
} else {
return { }
}
}
@Composable
private fun LifecycleDisposableEffect(
context: Context,
parentLifecycleOwner: LifecycleOwner,
) {
val activity = remember(context) {
context.getActivity()
}
val savedState = rememberSaveable { Bundle() }
if (!isCreated) {
onCreate(savedState) // do this in the UI thread to force it to be called before anything else
}
DisposableEffect(this) {
val unregisterLifecycle = registerParentLifecycleListener(parentLifecycleOwner) {
LifecycleEventObserver { owner, event ->
when {
/**
* Instance of the screen isn't recreated during config changes so skip this event
* to avoid crash while accessing to ViewModel with SavedStateHandle, because after
* ON_DESTROY, [androidx.lifecycle.SavedStateHandleController] is marked as not
* attached and next call of [registerSavedStateProvider] after recreating Activity
* on the same instance causing the crash.
*
* Also when activity is destroyed, but not finished, screen is not destroyed.
*
* In the case of Fragments, we unsubscribe before ON_DESTROY event, so there is no problem with this.
*/
event == Lifecycle.Event.ON_DESTROY && (activity?.isFinishing == false || activity?.isChangingConfigurations == true) ->
return@LifecycleEventObserver
// when the Application goes to background, perform save
event == Lifecycle.Event.ON_STOP ->
performSave(savedState)
}
lifecycle.safeHandleLifecycleEvent(event)
}
}
emitOnStartEvents()
onDispose {
unregisterLifecycle()
// when the screen goes to stack, perform save
performSave(savedState)
// notify lifecycle screen listeners
emitOnStopEvents()
}
}
}
private fun LifecycleRegistry.safeHandleLifecycleEvent(event: Lifecycle.Event) {
val currentState = currentState
val skippEvent = !currentState.isAtLeast(Lifecycle.State.INITIALIZED) ||
// Protection from double event sending from the parent
((event in startEvents || event in initEvents) && event.targetState <= currentState) ||
(event in stopEvents && event.targetState >= currentState)
// For debugging
// Log.d("ModoScreenAndroidAdapter", "safeHandleLifecycleEvent ${screen.screenKey} $event")
if (!skippEvent) {
handleLifecycleEvent(event)
}
}
companion object {
private val initEvents = arrayOf(
Lifecycle.Event.ON_CREATE
)
private val startEvents = arrayOf(
Lifecycle.Event.ON_START,
Lifecycle.Event.ON_RESUME
)
private val stopEvents = arrayOf(
Lifecycle.Event.ON_PAUSE,
Lifecycle.Event.ON_STOP
)
private val disposeEvents = arrayOf(
Lifecycle.Event.ON_DESTROY
)
/**
* Creates delegate for integration with android for the given [screen] or returns existed from cache.
*/
fun get(screen: Screen): ModoScreenAndroidAdapter =
ScreenModelStore.getOrPutDependency(
screen = screen,
name = "AndroidScreenLifecycleOwner",
onDispose = { it.onDispose(screen) }
) { ModoScreenAndroidAdapter() }
}
}