Skip to content

Commit 2d78e4a

Browse files
committed
add subscribe and unsubscribe userinfo
1 parent 06d9209 commit 2d78e4a

File tree

1 file changed

+63
-0
lines changed
  • core/src/main/java/com/segment/analytics/kotlin/core

1 file changed

+63
-0
lines changed

core/src/main/java/com/segment/analytics/kotlin/core/Analytics.kt

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,69 @@ open class Analytics protected constructor(
700700
return anonymousId()
701701
}
702702

703+
/**
704+
* Subscribes to UserInfo state changes.
705+
*
706+
* The handler is called immediately with the current UserInfo, then again whenever
707+
* the user's identity, traits, or referrer changes. The subscription remains active
708+
* for the lifetime of the Analytics instance unless explicitly unsubscribed.
709+
*
710+
* - Parameter handler: A closure called on the main queue with updated UserInfo.
711+
*
712+
* - Returns: A subscription ID that can be passed to `unsubscribe(_:)` to stop
713+
* receiving updates. If you don't need to unsubscribe, you can ignore the return value.
714+
*
715+
* - Note: Multiple calls create multiple independent subscriptions.
716+
*
717+
* ## Example
718+
* ```kotlin
719+
* // Subscribe for the lifetime of Analytics
720+
* analytics.subscribeToUserInfo { userInfo ->
721+
* print("User: ${userInfo.userId ?: userInfo.anonymousId}")
722+
* }
723+
*
724+
* // Subscribe with manual cleanup
725+
* val subscriptionId = analytics.subscribeToUserInfo { userInfo ->
726+
* // ... handle update
727+
* }
728+
* // Later, when you're done...
729+
* analytics.unsubscribe(subscriptionId)
730+
* ```
731+
*
732+
*/
733+
suspend fun subscribeToUserInfo(handler: (UserInfo) -> Unit) =
734+
store.subscribe(
735+
this,
736+
UserInfo::class,
737+
initialState = true,
738+
handler = handler,
739+
queue = fileIODispatcher
740+
)
741+
742+
/**
743+
* Unsubscribes from state updates.
744+
*
745+
* Stops receiving updates for the subscription associated with the given ID.
746+
* After calling this, the handler will no longer be invoked for state changes.
747+
*
748+
* - Parameter id: The subscription ID returned from a previous subscribe call.
749+
*
750+
* - Note: Unsubscribing an already-unsubscribed or invalid ID is a no-op.
751+
*
752+
* ## Example
753+
* ```kotlin
754+
* val id = analytics.subscribeToUserInfo { userInfo ->
755+
* print("User changed: ${userInfo.userId ?: "anonymous"}")
756+
* }
757+
*
758+
* // Later, stop listening
759+
* analytics.unsubscribe(id)
760+
* ```
761+
*/
762+
suspend fun unsubscribe(id: Int) {
763+
store.unsubscribe(id)
764+
}
765+
703766
/**
704767
* Retrieve the version of this library in use.
705768
* - Returns: A string representing the version in "BREAKING.FEATURE.FIX" format.

0 commit comments

Comments
 (0)