@@ -18,6 +18,7 @@ import com.segment.analytics.kotlin.android.utilities.DeepLinkUtils
18
18
import com.segment.analytics.kotlin.core.Analytics
19
19
import com.segment.analytics.kotlin.core.Storage
20
20
import com.segment.analytics.kotlin.core.platform.Plugin
21
+ import kotlinx.coroutines.Dispatchers
21
22
import kotlinx.coroutines.launch
22
23
import kotlinx.serialization.json.buildJsonObject
23
24
import kotlinx.serialization.json.put
@@ -69,7 +70,14 @@ class AndroidLifecyclePlugin() : Application.ActivityLifecycleCallbacks, Default
69
70
application.registerActivityLifecycleCallbacks(this )
70
71
if (useLifecycleObserver) {
71
72
lifecycle = ProcessLifecycleOwner .get().lifecycle
72
- lifecycle.addObserver(this )
73
+ // NOTE: addObserver is required to run on UI thread,
74
+ // though we made it compatible to run from background thread,
75
+ // there is a chance that lifecycle events get lost if init
76
+ // analytics from background (i.e. analytics is init, but
77
+ // lifecycle hook is yet to be registered.
78
+ runOnMainThread {
79
+ lifecycle.addObserver(this )
80
+ }
73
81
}
74
82
}
75
83
@@ -260,7 +268,14 @@ class AndroidLifecyclePlugin() : Application.ActivityLifecycleCallbacks, Default
260
268
application.unregisterActivityLifecycleCallbacks(this )
261
269
if (useLifecycleObserver) {
262
270
// only unregister if feature is enabled
263
- lifecycle.removeObserver(this )
271
+ runOnMainThread {
272
+ lifecycle.removeObserver(this )
273
+ }
274
+ }
275
+ }
276
+ private fun runOnMainThread (closure : () -> Unit ) {
277
+ analytics.analyticsScope.launch(Dispatchers .Main ) {
278
+ closure()
264
279
}
265
280
}
266
281
0 commit comments