From 19be960461ea3aec48eb2c436687fbd43d926e03 Mon Sep 17 00:00:00 2001 From: Bohdan Akimenko Date: Thu, 28 Nov 2024 20:31:24 +0200 Subject: [PATCH] Fix experiment run callback --- .../com/sdk/growthbook/GrowthBookSDK.kt | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/GrowthBook/src/commonMain/kotlin/com/sdk/growthbook/GrowthBookSDK.kt b/GrowthBook/src/commonMain/kotlin/com/sdk/growthbook/GrowthBookSDK.kt index dbe4aa0..252fbda 100644 --- a/GrowthBook/src/commonMain/kotlin/com/sdk/growthbook/GrowthBookSDK.kt +++ b/GrowthBook/src/commonMain/kotlin/com/sdk/growthbook/GrowthBookSDK.kt @@ -26,6 +26,7 @@ import kotlinx.serialization.json.JsonElement typealias GBTrackingCallback = (GBExperiment, GBExperimentResult?) -> Unit typealias GBFeatureUsageCallback = (featureKey: String, gbFeatureResult: GBFeatureResult) -> Unit +typealias GBExperimentRunCallback = (GBExperiment, GBExperimentResult) -> Unit /** * The main export of the libraries is a simple GrowthBook wrapper class @@ -40,6 +41,9 @@ class GrowthBookSDK() : FeaturesFlowDelegate { private var attributeOverrides: Map = emptyMap() private var forcedFeatures: Map = emptyMap() private var savedGroups: Map? = emptyMap() + private var assigned: MutableMap> = + mutableMapOf() + private var subscriptions: MutableList = mutableListOf() //@ThreadLocal internal companion object { @@ -193,11 +197,14 @@ class GrowthBookSDK() : FeaturesFlowDelegate { * The run method takes an Experiment object and returns an ExperimentResult */ fun run(experiment: GBExperiment): GBExperimentResult { - return GBExperimentEvaluator().evaluateExperiment( + val result = GBExperimentEvaluator().evaluateExperiment( context = gbContext, experiment = experiment, attributeOverrides = attributeOverrides ) + + fireSubscriptions(experiment, result) + return result } /** @@ -283,4 +290,25 @@ class GrowthBookSDK() : FeaturesFlowDelegate { ) featuresViewModel.fetchFeatures(gbContext.remoteEval, payload) } + + private fun fireSubscriptions(experiment: GBExperiment, experimentResult: GBExperimentResult) { + val key = experiment.key + // If assigned variation has changed, fire subscriptions + val prevAssignedExperiment = this.assigned[key] + if (prevAssignedExperiment == null + || prevAssignedExperiment.second.inExperiment != experimentResult.inExperiment + || prevAssignedExperiment.second.variationId != experimentResult.variationId + ) { + this.assigned[key] = experiment to experimentResult + } + for (callback in subscriptions) { + try { + callback.invoke(experiment, experimentResult) + } catch (e: Exception) { + if (gbContext.enableLogging) { + println("Error while run subscriptions: " + e.message) + } + } + } + } }