From 8752fe1e69cdb5f9419284b1838dc88b3df83bd7 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 23 Nov 2021 16:18:41 +0100 Subject: [PATCH] Analytics: observe the store and react --- .../analytics/impl/DefaultVectorAnalytics.kt | 46 +++++++++++++++---- 1 file changed, 36 insertions(+), 10 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt b/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt index 913f257a32..6164e2ded4 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt @@ -22,7 +22,10 @@ import com.posthog.android.Properties import im.vector.app.features.analytics.AnalyticsConfig import im.vector.app.features.analytics.VectorAnalytics import im.vector.app.features.analytics.store.AnalyticsStore +import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton @@ -34,6 +37,8 @@ class DefaultVectorAnalytics @Inject constructor( ) : VectorAnalytics { private var posthog: PostHog? = null + private var userConsent: Boolean = false + override fun getUserConsent(): Flow { return analyticsStore.userConsentFlow } @@ -61,8 +66,6 @@ class DefaultVectorAnalytics @Inject constructor( override suspend fun onSignOut() { // reset the analyticsId setAnalyticsId("") - // reset the library - posthog?.reset() } override fun init() { @@ -88,20 +91,43 @@ class DefaultVectorAnalytics @Inject constructor( // Enable or disable collection of ANDROID_ID (true) .collectDeviceId(false) .build() + + observeUserConsent() + observeAnalyticsId() + } + + @Suppress("EXPERIMENTAL_API_USAGE") + private fun observeAnalyticsId() { + GlobalScope.launch { + getAnalyticsId().onEach { + if (it.isEmpty()) { + posthog?.reset() + } else { + posthog?.identify(it) + } + } + } + } + + @Suppress("EXPERIMENTAL_API_USAGE") + private fun observeUserConsent() { + GlobalScope.launch { + getUserConsent().onEach { + userConsent = it + } + } } override fun capture(event: String, properties: Map?) { - posthog?.capture( - event, - properties.toPostHogProperties() - ) + posthog + ?.takeIf { userConsent } + ?.capture(event, properties.toPostHogProperties()) } override fun screen(name: String, properties: Map?) { - posthog?.screen( - name, - properties.toPostHogProperties() - ) + posthog + ?.takeIf { userConsent } + ?.screen(name, properties.toPostHogProperties()) } private fun Map?.toPostHogProperties(): Properties? {