Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix experiment run callback #155

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -40,6 +41,9 @@ class GrowthBookSDK() : FeaturesFlowDelegate {
private var attributeOverrides: Map<String, Any> = emptyMap()
private var forcedFeatures: Map<String, JsonElement> = emptyMap()
private var savedGroups: Map<String, Any>? = emptyMap()
private var assigned: MutableMap<String, Pair<GBExperiment, GBExperimentResult>> =
mutableMapOf()
private var subscriptions: MutableList<GBExperimentRunCallback> = mutableListOf()

//@ThreadLocal
internal companion object {
Expand Down Expand Up @@ -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
}

/**
Expand Down Expand Up @@ -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)
}
}
}
}
}
Loading