Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions posthog-android/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## Next

- feat: implement setPersonProps method ([#369](https://github.com/PostHog/posthog-android/pull/369))

## 3.28.1 - 2026-01-09

- fix: Allow flag property overrides via `setPersonPropertiesForFlags`, `setGroupPropertiesForFlags` without person processing ([#365](https://github.com/PostHog/posthog-android/issues/365))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ public class PostHogFake : PostHogInterface {
override fun flush() {
}

override fun setPersonProperties(
userPropertiesToSet: Map<String, Any>?,
userPropertiesToSetOnce: Map<String, Any>?,
) {
}

override fun setPersonPropertiesForFlags(
userProperties: Map<String, Any>,
reloadFeatureFlags: Boolean,
Expand Down
2 changes: 2 additions & 0 deletions posthog/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## Next

- feat: implement setPersonProps method ([#369](https://github.com/PostHog/posthog-android/pull/369))

## 6.1.0 - 2025-01-09

- fix: Allow flag property overrides via `setPersonPropertiesForFlags`, `setGroupPropertiesForFlags` without person processing ([#365](https://github.com/PostHog/posthog-android/issues/365))
Expand Down
4 changes: 4 additions & 0 deletions posthog/api/posthog.api
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public final class com/posthog/PostHog : com/posthog/PostHogStateless, com/posth
public fun resetPersonPropertiesForFlags (Z)V
public fun screen (Ljava/lang/String;Ljava/util/Map;)V
public fun setGroupPropertiesForFlags (Ljava/lang/String;Ljava/util/Map;Z)V
public fun setPersonProperties (Ljava/util/Map;Ljava/util/Map;)V
public fun setPersonPropertiesForFlags (Ljava/util/Map;Z)V
public fun setup (Lcom/posthog/PostHogConfig;)V
public fun startSession ()V
Expand Down Expand Up @@ -73,6 +74,7 @@ public final class com/posthog/PostHog$Companion : com/posthog/PostHogInterface
public final fun resetSharedInstance ()V
public fun screen (Ljava/lang/String;Ljava/util/Map;)V
public fun setGroupPropertiesForFlags (Ljava/lang/String;Ljava/util/Map;Z)V
public fun setPersonProperties (Ljava/util/Map;Ljava/util/Map;)V
public fun setPersonPropertiesForFlags (Ljava/util/Map;Z)V
public fun setup (Lcom/posthog/PostHogConfig;)V
public fun startSession ()V
Expand Down Expand Up @@ -286,6 +288,7 @@ public abstract interface class com/posthog/PostHogInterface : com/posthog/PostH
public abstract fun resetPersonPropertiesForFlags (Z)V
public abstract fun screen (Ljava/lang/String;Ljava/util/Map;)V
public abstract fun setGroupPropertiesForFlags (Ljava/lang/String;Ljava/util/Map;Z)V
public abstract fun setPersonProperties (Ljava/util/Map;Ljava/util/Map;)V
public abstract fun setPersonPropertiesForFlags (Ljava/util/Map;Z)V
public abstract fun startSession ()V
public abstract fun startSessionReplay (Z)V
Expand All @@ -305,6 +308,7 @@ public final class com/posthog/PostHogInterface$DefaultImpls {
public static synthetic fun resetPersonPropertiesForFlags$default (Lcom/posthog/PostHogInterface;ZILjava/lang/Object;)V
public static synthetic fun screen$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)V
public static synthetic fun setGroupPropertiesForFlags$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/util/Map;ZILjava/lang/Object;)V
public static synthetic fun setPersonProperties$default (Lcom/posthog/PostHogInterface;Ljava/util/Map;Ljava/util/Map;ILjava/lang/Object;)V
public static synthetic fun setPersonPropertiesForFlags$default (Lcom/posthog/PostHogInterface;Ljava/util/Map;ZILjava/lang/Object;)V
public static synthetic fun startSessionReplay$default (Lcom/posthog/PostHogInterface;ZILjava/lang/Object;)V
}
Expand Down
85 changes: 85 additions & 0 deletions posthog/src/main/java/com/posthog/PostHog.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import com.posthog.internal.PostHogSessionManager
import com.posthog.internal.PostHogThreadFactory
import com.posthog.internal.personPropertiesContext
import com.posthog.internal.replay.PostHogSessionReplayHandler
import com.posthog.internal.sortMapRecursively
import com.posthog.internal.surveys.PostHogSurveysHandler
import com.posthog.vendor.uuid.TimeBasedEpochGenerator
import java.util.Date
Expand Down Expand Up @@ -54,11 +55,15 @@ public class PostHog private constructor(
private val personProcessingLock: Any = Any()

private val featureFlagsCalledLock = Any()
private val cachedPersonPropertiesLock = Any()

private var remoteConfig: PostHogRemoteConfig? = null
private var replayQueue: PostHogQueueInterface? = null
private val featureFlagsCalled = mutableMapOf<String, MutableList<Any?>>()

// Used to deduplicate setPersonProperties calls
private var cachedPersonPropertiesHash: String? = null

private var sessionReplayHandler: PostHogSessionReplayHandler? = null
private var surveysHandler: PostHogSurveysHandler? = null

Expand Down Expand Up @@ -720,6 +725,76 @@ public class PostHog private constructor(
}
}

public override fun setPersonProperties(
userPropertiesToSet: Map<String, Any>?,
userPropertiesToSetOnce: Map<String, Any>?,
) {
if (!isEnabled()) {
return
}

if (userPropertiesToSet.isNullOrEmpty() && userPropertiesToSetOnce.isNullOrEmpty()) {
return
}
Comment on lines +736 to +738

@ioannisj ioannisj Jan 16, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

js does the same, but just curious in general, how do we allow clearing person properties? My understanding is that $set is additive, should we have an unsetPersonProperties() counterpart that sets $unset property?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JS SDK does not have $unset but yeah good call, nor resetPersonProperties(), i will keep as is for now like the JS SDK

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


if (!requirePersonProcessing("setPersonProperties")) {
return
}

val currentDistinctId = this.distinctId

// Calculate hash to deduplicate calls with the same properties
val hash = getPersonPropertiesHash(currentDistinctId, userPropertiesToSet, userPropertiesToSetOnce)

synchronized(cachedPersonPropertiesLock) {
if (cachedPersonPropertiesHash == hash) {
config?.logger?.log("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")
return
}
cachedPersonPropertiesHash = hash
}

// Update person properties for flags (setOnce properties are applied first, then set properties override)
val allProperties = mutableMapOf<String, Any>()
userPropertiesToSetOnce?.let { allProperties.putAll(it) }
userPropertiesToSet?.let { allProperties.putAll(it) }
if (allProperties.isNotEmpty()) {
setPersonPropertiesForFlags(allProperties, reloadFeatureFlags = false)
}

// Send the $set event
capture(
PostHogEventName.SET.event,
distinctId = currentDistinctId,
userProperties = userPropertiesToSet,
userPropertiesSetOnce = userPropertiesToSetOnce,
)
}

/**
* Computes a hash for deduplicating setPersonProperties calls.
* Similar to the JS SDK, this creates a JSON string representation of the properties.
* Keys are sorted recursively to ensure deterministic hashing regardless of map insertion order.
*/
private fun getPersonPropertiesHash(
distinctId: String,
userPropertiesToSet: Map<String, Any>?,
userPropertiesToSetOnce: Map<String, Any>?,
): String {
// Sort keys recursively to ensure deterministic hashing regardless of map insertion order
val sortedSet = userPropertiesToSet?.let { sortMapRecursively(it) }
val sortedSetOnce = userPropertiesToSetOnce?.let { sortMapRecursively(it) }

// Create a consistent JSON-like string representation similar to JS SDK's jsonStringify
val hashData =
sortedMapOf(
"distinct_id" to distinctId,
"userPropertiesToSet" to sortedSet,
"userPropertiesToSetOnce" to sortedSetOnce,
)
return config?.serializer?.serializeObject(hashData) ?: hashData.toString()
Comment thread
marandaneto marked this conversation as resolved.
Resolved
}

private fun hasPersonProcessing(): Boolean {
return !(
config?.personProfiles == PersonProfiles.NEVER ||
Expand Down Expand Up @@ -1045,6 +1120,9 @@ public class PostHog private constructor(
getPreferences().clear(except = except.toList())
remoteConfig?.clear()
featureFlagsCalled.clear()
synchronized(cachedPersonPropertiesLock) {
cachedPersonPropertiesHash = null
}
synchronized(identifiedLock) {
isIdentifiedLoaded = false
}
Expand Down Expand Up @@ -1317,6 +1395,13 @@ public class PostHog private constructor(
shared.flush()
}

public override fun setPersonProperties(
userPropertiesToSet: Map<String, Any>?,
userPropertiesToSetOnce: Map<String, Any>?,
) {
shared.setPersonProperties(userPropertiesToSet, userPropertiesToSetOnce)
}

public override fun setPersonPropertiesForFlags(
userProperties: Map<String, Any>,
reloadFeatureFlags: Boolean,
Expand Down
19 changes: 19 additions & 0 deletions posthog/src/main/java/com/posthog/PostHogInterface.kt
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,25 @@ public interface PostHogInterface : PostHogCoreInterface {
*/
public fun getSessionId(): UUID?

/**
* Sets properties on the person profile associated with the current distinct_id.
* Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)
*
* Updates user properties that are stored with the person profile in PostHog.
* If `personProfiles` is set to `IDENTIFIED_ONLY` and no profile exists, this will create one.
*
* This method sends a `$set` event to PostHog.
*
* @param userPropertiesToSet Optional: Properties to store about the user. These will overwrite existing values.
* @param userPropertiesToSetOnce Optional: Properties to store about the user only if not previously set.
* Note: For feature flag evaluations, if the same key is present in both parameters,
* the value from userPropertiesToSet will take precedence.
*/
public fun setPersonProperties(
userPropertiesToSet: Map<String, Any>? = null,
userPropertiesToSetOnce: Map<String, Any>? = null,
)

/**
* Sets person properties that will be included in feature flag evaluation requests.
*
Expand Down
29 changes: 29 additions & 0 deletions posthog/src/main/java/com/posthog/internal/PostHogUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import java.io.IOException
import java.io.InterruptedIOException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.SortedMap
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService

Expand Down Expand Up @@ -73,3 +74,31 @@ public fun Thread.interruptSafely() {
// ignore
}
}

/**
* Recursively sorts a map by keys at all levels.
* This is useful for creating deterministic string representations of maps.
*/
internal fun sortMapRecursively(map: Map<String, Any?>): SortedMap<String, Any?> {
val sortedMap = sortedMapOf<String, Any?>()
for ((key, value) in map) {
sortedMap[key] = sortValueRecursively(value)
}
return sortedMap
}

/**
* Recursively sorts values that are maps, lists, or arrays containing maps.
*/
private fun sortValueRecursively(value: Any?): Any? {
return when (value) {
is Map<*, *> -> {
@Suppress("UNCHECKED_CAST")
val stringKeyMap = value.filterKeys { it is String } as Map<String, Any?>
sortMapRecursively(stringKeyMap)
}
is List<*> -> value.map { item -> sortValueRecursively(item) }
is Array<*> -> value.map { item -> sortValueRecursively(item) }
else -> value
}
}
Loading
Loading