From 61a6ed1d3472fb816e891a69dfe35bd6bd0bce22 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 18:57:38 -0400 Subject: [PATCH 1/2] feat!: remove defaultValue from getFeatureFlag The canonical client signature has no default and iOS, Flutter and RN have none. A fallback was also reported as the flag value in $feature_flag_called. A disabled SDK now returns null; isFeatureEnabled keeps its defaultValue. --- .changeset/android-v4-major.md | 1 + .../PostHogSurveysLinkedFlagVariantTest.kt | 2 +- .../surveys/PostHogSurveysSelectionTest.kt | 2 +- posthog/api/posthog.api | 10 +-- posthog/src/main/java/com/posthog/PostHog.kt | 10 +-- .../main/java/com/posthog/PostHogInterface.kt | 13 ++- .../com/posthog/PostHogFeatureFlagsTest.kt | 84 ++++++++++++------- .../java/com/posthog/PostHogFake.kt | 1 - 8 files changed, 77 insertions(+), 46 deletions(-) diff --git a/.changeset/android-v4-major.md b/.changeset/android-v4-major.md index b24de8f7e..79cf0f4cb 100644 --- a/.changeset/android-v4-major.md +++ b/.changeset/android-v4-major.md @@ -8,6 +8,7 @@ - **Breaking:** remove the deprecated `evaluationEnvironments` config option; use `evaluationContexts` instead - **Breaking:** remove the deprecated `getFeatureFlagPayload()`; use `getFeatureFlagResult(key)?.payload` instead - **Breaking:** remove the deprecated `PostHogSessionReplayConfig.debouncerDelayMs`; use `throttleDelayMs` instead +- **Breaking:** remove the `defaultValue` parameter from `getFeatureFlag()`, which returns `null` for a flag with no value or a disabled SDK, so use `getFeatureFlag(key) ?: default` instead; a positional `Boolean` second argument now sets `sendFeatureFlagEvent`, and `$feature_flag_called` no longer reports a fallback from `getFeatureFlag()` or `isFeatureEnabled()` as the flag's value - **Breaking:** return `null` instead of the raw string for a malformed, empty or whitespace-only feature flag payload from `getFeatureFlagResult(key)?.payload`; payloads must be valid JSON (a JSON `null` payload now also reads as `null` instead of the string `"null"`) - **Breaking:** make SDK-internal helpers in the `com.posthog.internal` and `com.posthog.android.replay.internal` packages non-public - **Breaking:** remove the deprecated `remoteConfig` config option; the SDK now always loads remote config at setup diff --git a/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysLinkedFlagVariantTest.kt b/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysLinkedFlagVariantTest.kt index 230796ec2..b7512e36d 100644 --- a/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysLinkedFlagVariantTest.kt +++ b/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysLinkedFlagVariantTest.kt @@ -67,7 +67,7 @@ internal class PostHogSurveysLinkedFlagVariantTest( val value = flagValues[it.getArgument(0)] value == true || value is String } - whenever(postHog.getFeatureFlag(any(), anyOrNull(), anyOrNull())).thenAnswer { + whenever(postHog.getFeatureFlag(any(), anyOrNull())).thenAnswer { flagValues[it.getArgument(0)] } val survey = diff --git a/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysSelectionTest.kt b/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysSelectionTest.kt index 626a0bbc0..2b27a1cbc 100644 --- a/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysSelectionTest.kt +++ b/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysSelectionTest.kt @@ -77,7 +77,7 @@ internal class PostHogSurveysSelectionTest { val value = flags[it.getArgument(0)] value == true || value is String } - whenever(postHog.getFeatureFlag(any(), anyOrNull(), anyOrNull())).thenAnswer { flags[it.getArgument(0)] } + whenever(postHog.getFeatureFlag(any(), anyOrNull())).thenAnswer { flags[it.getArgument(0)] } val integration = PostHogSurveysIntegration(context, config) integration.install(postHog) try { diff --git a/posthog/api/posthog.api b/posthog/api/posthog.api index fdf89f65f..fd62b904c 100644 --- a/posthog/api/posthog.api +++ b/posthog/api/posthog.api @@ -38,7 +38,7 @@ public final class com/posthog/PostHog : com/posthog/PostHogStateless, com/posth public fun getAnonymousId ()Ljava/lang/String; public fun getConfig ()Lcom/posthog/PostHogConfig; public fun getDeviceId ()Ljava/lang/String; - public fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Boolean;)Ljava/lang/Object; + public fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Boolean;)Ljava/lang/Object; public fun getFeatureFlagResult (Ljava/lang/String;Ljava/lang/Boolean;)Lcom/posthog/FeatureFlagResult; public fun getLogger ()Lcom/posthog/logs/PostHogLogger; public fun getSessionId ()Ljava/util/UUID; @@ -87,7 +87,7 @@ public final class com/posthog/PostHog$Companion : com/posthog/PostHogInterface public fun getAnonymousId ()Ljava/lang/String; public fun getConfig ()Lcom/posthog/PostHogConfig; public fun getDeviceId ()Ljava/lang/String; - public fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Boolean;)Ljava/lang/Object; + public fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Boolean;)Ljava/lang/Object; public fun getFeatureFlagResult (Ljava/lang/String;Ljava/lang/Boolean;)Lcom/posthog/FeatureFlagResult; public fun getLogger ()Lcom/posthog/logs/PostHogLogger; public fun getSessionId ()Ljava/util/UUID; @@ -402,8 +402,8 @@ public abstract interface class com/posthog/PostHogInterface : com/posthog/PostH public abstract fun getAnonymousId ()Ljava/lang/String; public abstract fun getConfig ()Lcom/posthog/PostHogConfig; public abstract fun getDeviceId ()Ljava/lang/String; - public abstract fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Boolean;)Ljava/lang/Object; - public static synthetic fun getFeatureFlag$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Boolean;ILjava/lang/Object;)Ljava/lang/Object; + public abstract fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Boolean;)Ljava/lang/Object; + public static synthetic fun getFeatureFlag$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Boolean;ILjava/lang/Object;)Ljava/lang/Object; public abstract fun getFeatureFlagResult (Ljava/lang/String;Ljava/lang/Boolean;)Lcom/posthog/FeatureFlagResult; public static synthetic fun getFeatureFlagResult$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Boolean;ILjava/lang/Object;)Lcom/posthog/FeatureFlagResult; public abstract fun getLogger ()Lcom/posthog/logs/PostHogLogger; @@ -448,7 +448,7 @@ public final class com/posthog/PostHogInterface$DefaultImpls { public static synthetic fun captureFeatureView$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)V public static synthetic fun captureLog$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Lcom/posthog/logs/PostHogLogSeverity;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;ILjava/lang/Object;)V public static synthetic fun capturePushNotificationOpened$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;Ljava/lang/String;ILjava/lang/Object;)V - public static synthetic fun getFeatureFlag$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Boolean;ILjava/lang/Object;)Ljava/lang/Object; + public static synthetic fun getFeatureFlag$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Boolean;ILjava/lang/Object;)Ljava/lang/Object; public static synthetic fun getFeatureFlagResult$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Boolean;ILjava/lang/Object;)Lcom/posthog/FeatureFlagResult; public static synthetic fun group$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)V public static synthetic fun isFeatureEnabled$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;ZLjava/lang/Boolean;ILjava/lang/Object;)Z diff --git a/posthog/src/main/java/com/posthog/PostHog.kt b/posthog/src/main/java/com/posthog/PostHog.kt index f53f2572a..9a1e28e0c 100644 --- a/posthog/src/main/java/com/posthog/PostHog.kt +++ b/posthog/src/main/java/com/posthog/PostHog.kt @@ -2109,7 +2109,7 @@ public class PostHog private constructor( defaultValue: Boolean, sendFeatureFlagEvent: Boolean?, ): Boolean { - val value = getFeatureFlag(key, defaultValue, sendFeatureFlagEvent) + val value = getFeatureFlag(key, sendFeatureFlagEvent) ?: defaultValue if (value is Boolean) { return value @@ -2190,11 +2190,10 @@ public class PostHog private constructor( public override fun getFeatureFlag( key: String, - defaultValue: Any?, sendFeatureFlagEvent: Boolean?, ): Any? { - if (!isEnabled()) return defaultValue - val flagValue = remoteConfig?.getFeatureFlagResult(key)?.value ?: defaultValue + if (!isEnabled()) return null + val flagValue = remoteConfig?.getFeatureFlagResult(key)?.value sendFeatureFlagCalled(key, flagValue, sendFeatureFlagEvent) return flagValue } @@ -2847,9 +2846,8 @@ public class PostHog private constructor( public override fun getFeatureFlag( key: String, - defaultValue: Any?, sendFeatureFlagEvent: Boolean?, - ): Any? = shared.getFeatureFlag(key, defaultValue = defaultValue, sendFeatureFlagEvent) + ): Any? = shared.getFeatureFlag(key, sendFeatureFlagEvent) override fun getAllFeatureFlags(): List? { return shared.getAllFeatureFlags() diff --git a/posthog/src/main/java/com/posthog/PostHogInterface.kt b/posthog/src/main/java/com/posthog/PostHogInterface.kt index cf0dd630f..7ffb42215 100644 --- a/posthog/src/main/java/com/posthog/PostHogInterface.kt +++ b/posthog/src/main/java/com/posthog/PostHogInterface.kt @@ -186,16 +186,21 @@ public interface PostHogInterface : PostHogCoreInterface { ): Boolean /** - * Returns the feature flag + * Returns the feature flag value, or null if the flag has no value or the SDK is disabled. + * Use `?:` for a fallback; it is never reported in the $feature_flag_called event. + * + * ```kotlin + * val variant = PostHog.getFeatureFlag("my-flag") ?: "control" + * ``` + * * Docs https://posthog.com/docs/feature-flags and https://posthog.com/docs/experiments * @param key the Key - * @param defaultValue the default value if not found * @param sendFeatureFlagEvent (optional) If false, we won't send an $feature_flag_called event to PostHog. - * @return The feature flag value, or [defaultValue] if not found. + * Defaults to [PostHogConfig.sendFeatureFlagEvent]. + * @return The feature flag value, or null if not found. */ public fun getFeatureFlag( key: String, - defaultValue: Any? = null, sendFeatureFlagEvent: Boolean? = null, ): Any? diff --git a/posthog/src/test/java/com/posthog/PostHogFeatureFlagsTest.kt b/posthog/src/test/java/com/posthog/PostHogFeatureFlagsTest.kt index 8c02709ce..9da19fd32 100644 --- a/posthog/src/test/java/com/posthog/PostHogFeatureFlagsTest.kt +++ b/posthog/src/test/java/com/posthog/PostHogFeatureFlagsTest.kt @@ -348,49 +348,77 @@ internal class PostHogFeatureFlagsTest { sut.close() } - @Test - fun `getFeatureFlag with non-existent flag sends defaultValue in event`() { - val file = File("src/test/resources/json/basic-flags-with-non-active-flags.json") - val responseFlagsApi = file.readText() - + private fun assertMissingFlagReportsNoValue(read: (PostHogInterface) -> Unit) { val http = mockHttp( response = MockResponse() - .setBody(responseFlagsApi), + .setBody(File("src/test/resources/json/basic-flags-with-non-active-flags.json").readText()), ) - http.enqueue( - MockResponse() - .setBody(""), - ) - val url = http.url("/") - val sut = getSut(url.toString(), preloadFeatureFlags = false, sendFeatureFlagEvent = true) + http.enqueue(MockResponse().setBody("")) + val sut = getSut(http.url("/").toString(), preloadFeatureFlags = false, sendFeatureFlagEvent = true) sut.reloadFeatureFlags() - remoteConfigExecutor.shutdownAndAwaitTermination() - - // remove from the http queue http.takeRequest() - val defaultValue = "my-default" - val result = sut.getFeatureFlag("nonExistentFlag", defaultValue) - + read(sut) queueExecutor.shutdownAndAwaitTermination() - // Function should return the defaultValue - assertEquals(defaultValue, result) + val batch = serializer.deserialize(http.takeRequest().body.unGzip().reader()) + val theEvent = batch.batch.first() + assertEquals("\$feature_flag_called", theEvent.event) + assertEquals("nonExistentFlag", theEvent.properties!!["\$feature_flag"]) + assertEquals("", theEvent.properties!!["\$feature_flag_response"]) + sut.close() + } - val request = http.takeRequest() - val content = request.body.unGzip() - val batch = serializer.deserialize(content.reader()) + @Test + fun `getFeatureFlag returns null and reports no value for a missing flag`() { + assertMissingFlagReportsNoValue { sut -> + assertNull(sut.getFeatureFlag("nonExistentFlag")) + } + } - val theEvent = batch.batch.firstOrNull() - assertEquals("\$feature_flag_called", theEvent?.event) - // The event's $feature_flag_response should be the defaultValue, not null - assertEquals(defaultValue, theEvent?.properties!!["\$feature_flag_response"]) - assertEquals("nonExistentFlag", theEvent.properties!!["\$feature_flag"]) + @Test + fun `isFeatureEnabled returns the default but does not report it for a missing flag`() { + assertMissingFlagReportsNoValue { sut -> + assertTrue(sut.isFeatureEnabled("nonExistentFlag", defaultValue = true)) + } + } + + @Test + fun `isFeatureEnabled prefers a false flag value over the default`() { + val http = + mockHttp( + response = + MockResponse() + .setBody(File("src/test/resources/json/basic-flags-with-non-active-flags.json").readText()), + ) + val sut = getSut(http.url("/").toString(), preloadFeatureFlags = false) + + sut.reloadFeatureFlags() + remoteConfigExecutor.shutdownAndAwaitTermination() + + assertFalse(sut.isFeatureEnabled("IAmInactive", defaultValue = true)) + } + + @Test + fun `disabled SDK returns null from getFeatureFlag and the default from isFeatureEnabled`() { + val http = + mockHttp( + response = + MockResponse() + .setBody(File("src/test/resources/json/basic-flags-with-non-active-flags.json").readText()), + ) + val sut = getSut(http.url("/").toString(), preloadFeatureFlags = false) + + sut.reloadFeatureFlags() + remoteConfigExecutor.shutdownAndAwaitTermination() sut.close() + + assertNull(sut.getFeatureFlag("4535-funnel-bar-viz")) + assertTrue(sut.isFeatureEnabled("IAmInactive", defaultValue = true)) } @Test diff --git a/posthog/src/testFixtures/java/com/posthog/PostHogFake.kt b/posthog/src/testFixtures/java/com/posthog/PostHogFake.kt index dd5f42273..aea4857af 100644 --- a/posthog/src/testFixtures/java/com/posthog/PostHogFake.kt +++ b/posthog/src/testFixtures/java/com/posthog/PostHogFake.kt @@ -94,7 +94,6 @@ public class PostHogFake : PostHogInterface { override fun getFeatureFlag( key: String, - defaultValue: Any?, sendFeatureFlagEvent: Boolean?, ): Any? { return null From f72e8e1ef53c1b35bd39060d7893a89f924e6a03 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 19:12:12 -0400 Subject: [PATCH 2/2] feat!: remove PostHogConfig.onFeatureFlags in favor of the listener The onFeatureFlags() listener can be registered before setup(), gets bootstrapped flags, and is removable, so the config field no longer adds anything. iOS and posthog-js only have the listener form. --- .changeset/android-v4-major.md | 3 +- .../PostHogAndroidEventSnapshotsTest.kt | 5 ++- .../java/com/posthog/android/sample/MyApp.kt | 2 - .../com/posthog/server/PostHogConfigTest.kt | 1 - posthog/api/posthog.api | 6 +-- posthog/src/main/java/com/posthog/PostHog.kt | 28 +++++------- .../main/java/com/posthog/PostHogConfig.kt | 6 --- .../posthog/PostHogFeatureFlagsCallback.kt | 12 +++-- .../posthog/internal/PostHogRemoteConfig.kt | 6 +-- .../java/com/posthog/PostHogBootstrapTest.kt | 45 +++++-------------- .../java/com/posthog/PostHogConfigTest.kt | 5 --- 11 files changed, 36 insertions(+), 83 deletions(-) diff --git a/.changeset/android-v4-major.md b/.changeset/android-v4-major.md index 79cf0f4cb..f56d87caf 100644 --- a/.changeset/android-v4-major.md +++ b/.changeset/android-v4-major.md @@ -12,5 +12,6 @@ - **Breaking:** return `null` instead of the raw string for a malformed, empty or whitespace-only feature flag payload from `getFeatureFlagResult(key)?.payload`; payloads must be valid JSON (a JSON `null` payload now also reads as `null` instead of the string `"null"`) - **Breaking:** make SDK-internal helpers in the `com.posthog.internal` and `com.posthog.android.replay.internal` packages non-public - **Breaking:** remove the deprecated `remoteConfig` config option; the SDK now always loads remote config at setup -- **Breaking:** replace `PostHogOnFeatureFlags` with `PostHogFeatureFlagsCallback` in `PostHogConfig.onFeatureFlags` and `reloadFeatureFlags()`; it receives a `PostHogFeatureFlagsLoaded` with the enabled flags, their values, and `errorsLoading` +- **Breaking:** remove `PostHogConfig.onFeatureFlags`; call `PostHog.onFeatureFlags(callback)` before `setup()` instead, which also covers the first load +- **Breaking:** replace `PostHogOnFeatureFlags` with `PostHogFeatureFlagsCallback` in `reloadFeatureFlags()`; it receives a `PostHogFeatureFlagsLoaded` with the enabled flags, their values, and `errorsLoading` - Add `onFeatureFlags()` to get notified after every feature flags load (on the main thread on Android), returning a `PostHogFeatureFlagsSubscription` you can `unsubscribe()` diff --git a/posthog-android/src/test/java/com/posthog/android/PostHogAndroidEventSnapshotsTest.kt b/posthog-android/src/test/java/com/posthog/android/PostHogAndroidEventSnapshotsTest.kt index a29635090..e9912e7dd 100644 --- a/posthog-android/src/test/java/com/posthog/android/PostHogAndroidEventSnapshotsTest.kt +++ b/posthog-android/src/test/java/com/posthog/android/PostHogAndroidEventSnapshotsTest.kt @@ -24,6 +24,7 @@ import java.util.Date import java.util.TimeZone import java.util.UUID import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executor import java.util.concurrent.TimeUnit import java.util.zip.GZIPInputStream import kotlin.test.AfterTest @@ -67,8 +68,10 @@ internal class PostHogAndroidEventSnapshotsTest { fun `batch request and enriched event shapes match snapshot`() { val fixture = createFixture() val flagsLoaded = CountDownLatch(1) - fixture.config.onFeatureFlags = PostHogFeatureFlagsCallback { flagsLoaded.countDown() } val sut = fixture.client + // this test blocks the main thread, where listeners otherwise run + fixture.config.featureFlagsListenerExecutor = Executor { it.run() } + sut.onFeatureFlags { flagsLoaded.countDown() } sut.capture( event = "checkout completed", diff --git a/posthog-samples/posthog-android-sample/src/main/java/com/posthog/android/sample/MyApp.kt b/posthog-samples/posthog-android-sample/src/main/java/com/posthog/android/sample/MyApp.kt index bfdb0e45e..b1ebd89c4 100644 --- a/posthog-samples/posthog-android-sample/src/main/java/com/posthog/android/sample/MyApp.kt +++ b/posthog-samples/posthog-android-sample/src/main/java/com/posthog/android/sample/MyApp.kt @@ -2,7 +2,6 @@ package com.posthog.android.sample import android.app.Application import android.os.StrictMode -import com.posthog.PostHogFeatureFlagsCallback import com.posthog.android.PostHogAndroid import com.posthog.android.PostHogAndroidConfig @@ -39,7 +38,6 @@ class MyApp : Application() { sessionReplay = true preloadFeatureFlags = true sendFeatureFlagEvent = false - onFeatureFlags = PostHogFeatureFlagsCallback { print("feature flags loaded") } addBeforeSend { event -> if (event.event == "test_event") { null diff --git a/posthog-server/src/test/java/com/posthog/server/PostHogConfigTest.kt b/posthog-server/src/test/java/com/posthog/server/PostHogConfigTest.kt index f77668c76..f63920e87 100644 --- a/posthog-server/src/test/java/com/posthog/server/PostHogConfigTest.kt +++ b/posthog-server/src/test/java/com/posthog/server/PostHogConfigTest.kt @@ -180,7 +180,6 @@ internal class PostHogConfigTest { assertEquals(30, coreConfig.maxBatchSize) assertEquals(45, coreConfig.flushIntervalSeconds) assertEquals(mockEncryption, coreConfig.encryption) - assertNull(coreConfig.onFeatureFlags) } @Test diff --git a/posthog/api/posthog.api b/posthog/api/posthog.api index fd62b904c..9fdbdfe48 100644 --- a/posthog/api/posthog.api +++ b/posthog/api/posthog.api @@ -158,8 +158,8 @@ public class com/posthog/PostHogConfig { public static final field DEFAULT_MAX_QUEUE_SIZE I public static final field DEFAULT_US_ASSETS_HOST Ljava/lang/String; public static final field DEFAULT_US_HOST Ljava/lang/String; - public fun (Ljava/lang/String;Ljava/lang/String;ZZZIZLjava/util/List;ZIIIIIILcom/posthog/PostHogEncryption;Lcom/posthog/PostHogFeatureFlagsCallback;ZLkotlin/jvm/functions/Function1;ZLcom/posthog/PersonProfiles;ZLjava/net/Proxy;Lcom/posthog/surveys/PostHogSurveysConfig;Lcom/posthog/logs/PostHogLogsConfig;Lkotlin/jvm/functions/Function6;Lkotlin/jvm/functions/Function5;Lcom/posthog/errortracking/PostHogErrorTrackingConfig;Ljava/lang/String;Lcom/posthog/PostHogBootstrapConfig;Lkotlin/jvm/functions/Function3;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;ZZZIZLjava/util/List;ZIIIIIILcom/posthog/PostHogEncryption;Lcom/posthog/PostHogFeatureFlagsCallback;ZLkotlin/jvm/functions/Function1;ZLcom/posthog/PersonProfiles;ZLjava/net/Proxy;Lcom/posthog/surveys/PostHogSurveysConfig;Lcom/posthog/logs/PostHogLogsConfig;Lkotlin/jvm/functions/Function6;Lkotlin/jvm/functions/Function5;Lcom/posthog/errortracking/PostHogErrorTrackingConfig;Ljava/lang/String;Lcom/posthog/PostHogBootstrapConfig;Lkotlin/jvm/functions/Function3;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Ljava/lang/String;Ljava/lang/String;ZZZIZLjava/util/List;ZIIIIIILcom/posthog/PostHogEncryption;ZLkotlin/jvm/functions/Function1;ZLcom/posthog/PersonProfiles;ZLjava/net/Proxy;Lcom/posthog/surveys/PostHogSurveysConfig;Lcom/posthog/logs/PostHogLogsConfig;Lkotlin/jvm/functions/Function6;Lkotlin/jvm/functions/Function5;Lcom/posthog/errortracking/PostHogErrorTrackingConfig;Ljava/lang/String;Lcom/posthog/PostHogBootstrapConfig;Lkotlin/jvm/functions/Function3;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;ZZZIZLjava/util/List;ZIIIIIILcom/posthog/PostHogEncryption;ZLkotlin/jvm/functions/Function1;ZLcom/posthog/PersonProfiles;ZLjava/net/Proxy;Lcom/posthog/surveys/PostHogSurveysConfig;Lcom/posthog/logs/PostHogLogsConfig;Lkotlin/jvm/functions/Function6;Lkotlin/jvm/functions/Function5;Lcom/posthog/errortracking/PostHogErrorTrackingConfig;Ljava/lang/String;Lcom/posthog/PostHogBootstrapConfig;Lkotlin/jvm/functions/Function3;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun addBeforeSend (Lcom/posthog/PostHogBeforeSend;)V public final fun addIntegration (Lcom/posthog/PostHogIntegration;)V public final fun getBeforeSendList ()Ljava/util/List; @@ -189,7 +189,6 @@ public class com/posthog/PostHogConfig { public final fun getMaxQueueSize ()I public final fun getMaxRetries ()I public final fun getNetworkStatus ()Lcom/posthog/internal/PostHogNetworkStatus; - public final fun getOnFeatureFlags ()Lcom/posthog/PostHogFeatureFlagsCallback; public final fun getOptOut ()Z public final fun getPersistOptOut ()Z public final fun getPersonProfiles ()Lcom/posthog/PersonProfiles; @@ -241,7 +240,6 @@ public class com/posthog/PostHogConfig { public final fun setMaxQueueSize (I)V public final fun setMaxRetries (I)V public final fun setNetworkStatus (Lcom/posthog/internal/PostHogNetworkStatus;)V - public final fun setOnFeatureFlags (Lcom/posthog/PostHogFeatureFlagsCallback;)V public final fun setOptOut (Z)V public final fun setPersistOptOut (Z)V public final fun setPersonProfiles (Lcom/posthog/PersonProfiles;)V diff --git a/posthog/src/main/java/com/posthog/PostHog.kt b/posthog/src/main/java/com/posthog/PostHog.kt index 9a1e28e0c..44dd08b3c 100644 --- a/posthog/src/main/java/com/posthog/PostHog.kt +++ b/posthog/src/main/java/com/posthog/PostHog.kt @@ -430,8 +430,8 @@ public class PostHog private constructor( super.enabled = true - // Captured before any user callout below (integrations, session hooks, the bootstrap - // config callback), any of which may close() and so supersede setup's flags load. + // Captured before any user callout below (integrations, session hooks), any of + // which may close() and so supersede setup's flags load. val generation = featureFlagsGeneration // Queued before integrations install, so a reload one starts there can't hold the @@ -477,20 +477,16 @@ public class PostHog private constructor( // only because of testing in isolation, this flag is always enabled if (reloadFeatureFlags) { - // Bootstrap already seeded the flags in RemoteConfig's init; fire the flags-loaded - // callbacks now so listeners aren't blocked on the first network response. + // Bootstrap already seeded the flags in RemoteConfig's init, so replay can start + // without waiting for the first network response. if (remoteConfig?.hasBootstrapFlags() == true) { try { startSessionReplayOnFeatureFlagsLoaded() } catch (e: Throwable) { config.logger.log("Executing the internal feature flags callback failed: $e") } - notifyFeatureFlagsCallback(config.onFeatureFlags, remoteConfig?.getFeatureFlags(), errorsLoading = false) } - loadRemoteConfigRequest( - internalOnFeatureFlagsLoaded(generation), - config.onFeatureFlags, - ) + loadRemoteConfigRequest(internalOnFeatureFlagsLoaded(generation)) } // Reconcile a differing identified bootstrap after the setup reload is dispatched. @@ -1748,7 +1744,7 @@ public class PostHog private constructor( // only because of testing in isolation, this flag is always enabled if (reloadFeatureFlags) { - reloadFeatureFlags(config?.onFeatureFlags) + reloadFeatureFlags() } // we need to make sure the user props update is for the same user // otherwise they have to reset and identify again @@ -1777,7 +1773,7 @@ public class PostHog private constructor( // The identified state itself is not part of the flags request; reload only when the // caller supplied properties that can affect flag evaluation. if ((userProperties?.isNotEmpty() == true || userPropertiesSetOnce?.isNotEmpty() == true) && reloadFeatureFlags) { - reloadFeatureFlags(config?.onFeatureFlags) + reloadFeatureFlags() } } else if (!hasDifferentDistinctId && (userProperties?.isNotEmpty() == true || userPropertiesSetOnce?.isNotEmpty() == true)) { if (shouldCapturePersonPropertiesEvent( @@ -2005,7 +2001,7 @@ public class PostHog private constructor( // only because of testing in isolation, this flag is always enabled if (reloadFeatureFlags && reloadFeatureFlagsIfNewGroup) { - reloadFeatureFlags(config?.onFeatureFlags) + reloadFeatureFlags() } } @@ -2081,10 +2077,7 @@ public class PostHog private constructor( ) } - private fun loadRemoteConfigRequest( - internalOnFeatureFlags: ((errorsLoading: Boolean) -> Unit)?, - onFeatureFlags: PostHogFeatureFlagsCallback?, - ) { + private fun loadRemoteConfigRequest(internalOnFeatureFlags: ((errorsLoading: Boolean) -> Unit)?) { @Suppress("UNCHECKED_CAST") val groups = getPreferences().getValue(GROUPS) as? Map @@ -2100,7 +2093,6 @@ public class PostHog private constructor( anonymousId = anonymousId, groups, internalOnFeatureFlags, - onFeatureFlags, ) } @@ -2364,7 +2356,7 @@ public class PostHog private constructor( // reload flags as anon user // only because of testing in isolation, this flag is always enabled if (reloadFeatureFlags) { - reloadFeatureFlags(config?.onFeatureFlags) + reloadFeatureFlags() } } diff --git a/posthog/src/main/java/com/posthog/PostHogConfig.kt b/posthog/src/main/java/com/posthog/PostHogConfig.kt index f36d38c38..929b639dd 100644 --- a/posthog/src/main/java/com/posthog/PostHogConfig.kt +++ b/posthog/src/main/java/com/posthog/PostHogConfig.kt @@ -154,12 +154,6 @@ public open class PostHogConfig( * Defaults to no encryption */ public var encryption: PostHogEncryption? = null, - /** - * Hook that is called when feature flags are loaded, or loading them failed - * It receives a [PostHogFeatureFlagsLoaded]; see [PostHogFeatureFlagsCallback] for the thread it runs on - * Defaults to no callback - */ - public var onFeatureFlags: PostHogFeatureFlagsCallback? = null, /** * Enable Recording of Session Replays for Android * Requires Record user sessions to be enabled in the PostHog Project Settings diff --git a/posthog/src/main/java/com/posthog/PostHogFeatureFlagsCallback.kt b/posthog/src/main/java/com/posthog/PostHogFeatureFlagsCallback.kt index 355b9714f..6c39fc9f7 100644 --- a/posthog/src/main/java/com/posthog/PostHogFeatureFlagsCallback.kt +++ b/posthog/src/main/java/com/posthog/PostHogFeatureFlagsCallback.kt @@ -3,19 +3,17 @@ package com.posthog /** * Callback invoked when a feature flags load finishes, whether it succeeded or failed. * - * It's used by `PostHogConfig.onFeatureFlags`, `reloadFeatureFlags` and `onFeatureFlags`. - * - * For `PostHogConfig.onFeatureFlags` and `reloadFeatureFlags`, it runs on a background thread, or right - * away on the calling thread when no load is attempted (for example, the SDK is disabled). With - * bootstrapped flags, `PostHogConfig.onFeatureFlags` also runs once on the thread calling `setup()`, - * before the first load finishes. Hop to the main thread before touching UI. + * It's used by `onFeatureFlags` and `reloadFeatureFlags`. * * For `onFeatureFlags`, it runs on the main thread on Android, and on the SDK's background remote * config thread on the JVM. * + * For `reloadFeatureFlags`, it runs on a background thread, or right away on the calling thread when + * no load is attempted (for example, the SDK is disabled). Hop to the main thread before touching UI. + * * Example: * ```kotlin - * config.onFeatureFlags = PostHogFeatureFlagsCallback { loaded -> + * val subscription = PostHog.onFeatureFlags { loaded -> * if (!loaded.errorsLoading && "new-checkout" in loaded.flags) { * // The flag is enabled * } diff --git a/posthog/src/main/java/com/posthog/internal/PostHogRemoteConfig.kt b/posthog/src/main/java/com/posthog/internal/PostHogRemoteConfig.kt index f9bec33c9..b63a91e32 100644 --- a/posthog/src/main/java/com/posthog/internal/PostHogRemoteConfig.kt +++ b/posthog/src/main/java/com/posthog/internal/PostHogRemoteConfig.kt @@ -889,9 +889,9 @@ public class PostHogRemoteConfig( distinctId = distinctId, anonymousId = anonymousId, groups = groups, - // distinct(): the SDK's own listeners and config.onFeatureFlags are singleton - // instances reused across reloads, so appending each queued reload would fire - // them once per coalesced reload instead of once per response. + // distinct(): the SDK's own listeners are singleton instances reused across reloads, + // so appending each queued reload would fire them once per coalesced reload + // instead of once per response. internalOnFeatureFlags = (displaced?.internalOnFeatureFlags.orEmpty() + listOfNotNull(internalOnFeatureFlags)) .distinct(), diff --git a/posthog/src/test/java/com/posthog/PostHogBootstrapTest.kt b/posthog/src/test/java/com/posthog/PostHogBootstrapTest.kt index 8fb56afdd..689411319 100644 --- a/posthog/src/test/java/com/posthog/PostHogBootstrapTest.kt +++ b/posthog/src/test/java/com/posthog/PostHogBootstrapTest.kt @@ -18,13 +18,11 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicBoolean import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotEquals -import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @@ -51,7 +49,6 @@ internal class PostHogBootstrapTest { storagePrefix: String = tmpDir.newFolder().absolutePath, logger: TestLogger? = null, optOut: Boolean = false, - onFeatureFlags: PostHogFeatureFlagsCallback? = null, ): PostHogInterface { config = PostHogConfig(PROJECT_TOKEN, host).apply { @@ -63,7 +60,6 @@ internal class PostHogBootstrapTest { this.cachePreferences = cachePreferences this.bootstrap = bootstrap this.optOut = optOut - this.onFeatureFlags = onFeatureFlags if (logger != null) { this.logger = logger } @@ -372,25 +368,6 @@ internal class PostHogBootstrapTest { http.shutdown() } - @Test - fun `bootstrap flags fire the flags-loaded callback immediately`() { - var loaded: PostHogFeatureFlagsLoaded? = null - val sut = - getSut( - host = "http://127.0.0.1:1", - // the callback fires from setup's flag loading, before /config answers - reloadFeatureFlags = true, - bootstrap = PostHogBootstrapConfig(featureFlags = mapOf("beta-ui" to true, "checkout" to "test")), - onFeatureFlags = PostHogFeatureFlagsCallback { loaded = it }, - ) - - assertEquals(mapOf("beta-ui" to true, "checkout" to "test"), loaded!!.variants) - assertFalse(loaded!!.errorsLoading) - assertEquals(true, sut.getFeatureFlag("beta-ui", sendFeatureFlagEvent = false)) - - sut.close() - } - @Test fun `onFeatureFlags replays bootstrapped flags to a listener registered after setup`() { val sut = @@ -448,6 +425,7 @@ internal class PostHogBootstrapTest { // the integration's /flags request is held, so this can only be the bootstrap delivery val loaded = updates.poll(5, TimeUnit.SECONDS) assertEquals(mapOf("beta-ui" to true), loaded?.variants) + assertFalse(loaded!!.errorsLoading) } finally { subscription.unsubscribe() release.countDown() @@ -457,29 +435,26 @@ internal class PostHogBootstrapTest { } @Test - fun `closing from the bootstrap flags callback drops setup's load for listeners`() { + fun `closing from an integration drops the bootstrap delivery and setup's load for listeners`() { val http = mockHttp(total = 5, response = MockResponse().setBody("""{"hasFeatureFlags":false}""")) - val completed = LinkedBlockingQueue() - val first = AtomicBoolean(true) val config = PostHogConfig(PROJECT_TOKEN, http.url("/").toString()).apply { storagePrefix = tmpDir.newFolder().absolutePath cachePreferences = PostHogMemoryPreferences() bootstrap = PostHogBootstrapConfig(featureFlags = mapOf("beta-ui" to true)) - onFeatureFlags = - PostHogFeatureFlagsCallback { - // the bootstrap delivery closes the SDK; setup's own load completes later - if (first.compareAndSet(true, false)) PostHog.close() else completed.add(it) - } + addIntegration( + object : PostHogIntegration { + override fun install(postHog: PostHogInterface) { + PostHog.close() + } + }, + ) } try { PostHog.setup(config) + http.takeRequest(5, TimeUnit.SECONDS) - // setup's load notifies listeners just before this completion - assertNotNull(completed.poll(5, TimeUnit.SECONDS)) - - // close() cleared the snapshot, so only a load it superseded could refill it val updates = LinkedBlockingQueue() val subscription = PostHog.onFeatureFlags { updates.add(it) } assertNull(updates.poll(500, TimeUnit.MILLISECONDS)) diff --git a/posthog/src/test/java/com/posthog/PostHogConfigTest.kt b/posthog/src/test/java/com/posthog/PostHogConfigTest.kt index 7903540c3..db419ba18 100644 --- a/posthog/src/test/java/com/posthog/PostHogConfigTest.kt +++ b/posthog/src/test/java/com/posthog/PostHogConfigTest.kt @@ -105,11 +105,6 @@ internal class PostHogConfigTest { assertEquals(listOf("api.example.com"), config.tracingHeaders) } - @Test - fun `onFeatureFlags is not set by default`() { - assertNull(config.onFeatureFlags) - } - @Test fun `logger uses NoOp by default`() { assertTrue(config.logger is PostHogNoOpLogger)