> For the complete documentation index, see [llms.txt](https://docs.sudoplatform.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sudoplatform.com/guides/telephony/subscriptions.md).

# Subscriptions

The Telephony SDK supports real-time subscriptions that notify your application when resources change.

Subscriptions allow your application to be notified when a number finishes provisioning or when a message is received, without polling.&#x20;

#### Phone Number Subscriptions <a href="#virtual-presence-subscriptions" id="virtual-presence-subscriptions"></a>

Subscribe to phone number state changes (e.g., transitions to `PROVISIONING` or `ACTIVE`). Provide a unique subscription id to safely manage the subscription lifecycle.

**Subscribe**

{% tabs %}
{% tab title="Typescript" %}

```js
const subscriber: PhoneNumberSubscriber = {
  phoneNumberUpdated(phoneNumber: PhoneNumber): void {
    console.log('Phone number updated:', phoneNumber.id, phoneNumber.state)
    if (phoneNumber.state === PhoneNumberState.Active) {
      // The number is ready to use.
    }
  },
  connectionStatusChanged(state: ConnectionState): void {
    console.log('Connection state:', state)
    if (state === ConnectionState.Disconnected) {
      // Handle disconnection: consider re-subscribing
    }
  },
}

try {
  await telephonyClient.subscribeToPhoneNumbers('my-subscription-id', subscriber)
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
final class MyPhoneNumberSubscriber: PhoneNumberSubscriber {
    func phoneNumberUpdated(_ phoneNumber: PhoneNumber) {
        print("Phone number updated:", phoneNumber.id, phoneNumber.state)
    }

    func connectionStatusChanged(_ state: ConnectionState) {
        print("Connection state:", state)
        if state == .disconnected {
            // Handle disconnection: consider re-subscribing
        }
    }
}

do {
    let subscriber = MyPhoneNumberSubscriber()
    try await telephonyClient.subscribeToPhoneNumberUpdates(
        subscriptionId: "my-subscription-id",
        subscriber: subscriber
    )
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        withContext(Dispatchers.IO) {
            telephonyClient.subscribeToPhoneNumbers(
                "my-subscription-id",
                object : PhoneNumberSubscriber {
                    override fun phoneNumberUpdated(phoneNumber: PhoneNumber) {
                        println("Phone number updated: ${phoneNumber.id} ${phoneNumber.state}")
                    }

                    override fun connectionStatusChanged(state: Subscriber.ConnectionState) {
                        println("Connection state: $state")
                        if (state == Subscriber.ConnectionState.DISCONNECTED) {
                            // Handle disconnection: consider re-subscribing
                        }
                    }
                },
            )
        }
    } catch (e: PhoneNumberException) {
        // Handle/notify user of errors
    }
}

```

{% endtab %}
{% endtabs %}

**Unsubscribe**

{% tabs %}
{% tab title="Typescript" %}

```js
telephonyClient.unsubscribeFromPhoneNumbers('my-subscription-id')
```

{% endtab %}

{% tab title="Swift" %}

```swift
telephonyClient.unsubscribeFromPhoneNumberUpdates(subscriptionId: "my-subscription-id")
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        telephonyClient.unsubscribeFromPhoneNumbers('my-subscription-id')
        // or
        telephonyClient.unsubscribeAllFromPhoneNumbers()
    } catch (e: PhoneNumberException) {
        // Handle/notify the user of exception
    }
}
```

{% endtab %}
{% endtabs %}

#### Phone Message Subscriptions <a href="#data-holder-subscriptions" id="data-holder-subscriptions"></a>

Subscribe to phone message updates. Provide a unique subscription id to safely manage the subscription lifecycle.

**Subscribe**

{% tabs %}
{% tab title="Typescript" %}

```js
const subscriber: PhoneMessageSubscriber = {
  phoneMessageEvent(event: PhoneMessageEvent): void {
    console.log('Phone message event:', event.id, event.changeType)
    if (event.changeType === PhoneMessageChangeType.Received) {
      // The event carries no content; fetch the message to read it.
      void telephonyClient.getPhoneMessage(event.id)
    }
  },
  connectionStatusChanged(state: ConnectionState): void {
    console.log('Connection state:', state)
  },
}

try {
  await telephonyClient.subscribeToPhoneMessages('my-subscription-id', subscriber)
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
final class MyPhoneMessageSubscriber: PhoneMessageSubscriber {
    func phoneMessageUpdated(_ phoneMessages: [PhoneMessage]) {
        print("\(phoneMessages.count) phone messages updated")
        for pm in phoneMessages {
            print(pm.id, pm.conversationId)
        }
    }

    func connectionStatusChanged(_ state: ConnectionState) {
        print("Connection state:", state)
    }
}

do {
    let subscriber = MyPhoneMessageSubscriber()
    try await telephonyClient.subscribeToPhoneMessageEvents(
        subscriptionId: "my-subscription-id",
        subscriber: subscriber
    )
} catch {
    // Handle/notify user of errors
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        withContext(Dispatchers.IO) {
            telephonyClient.subscribeToPhoneMessages(
                "my-subscription-id",
                object : PhoneMessageSubscriber {
                    override fun phoneMessagesUpdated(phoneMessages: List<PhoneMessage>) {
                        println("${phoneMessages.size} phone messages updated")
                        for (pm in phoneMessages) {
                            println("${pm.id} ${pm.conversationId}")
                        }
                    }

                    override fun connectionStatusChanged(state: Subscriber.ConnectionState) {
                        println("Connection state: $state")
                    }
                },
            )
        }
    } catch (e: PhoneMessageException) {
        // Handle/notify user of errors
    }
}
```

{% endtab %}
{% endtabs %}

**Unsubscribe**

{% tabs %}
{% tab title="Typescript" %}

```js
telephonyClient.unsubscribeFromPhoneMessages('my-subscription-id')
```

{% endtab %}

{% tab title="Swift" %}

```swift
telephonyClient.unsubscribeFromPhoneMessageEvents(subscriptionId: "my-subscription-id")
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        telephonyClient.unsubscribeFromPhoneMessages('my-subscription-id')
        // or
        telephonyClient.unsubscribeAllFromPhoneMessages()
    } catch (e: PhoneMessageException) {
        // Handle/notify the user of exception
    }
}
```

{% endtab %}
{% endtabs %}

#### Connection State <a href="#connection-state" id="connection-state"></a>

All subscription interfaces include a `connectionStatusChanged` callback that notifies you when the subscription connection state changes. Your subscriber will not receive resource update events until the connection state is `CONNECTED`, and will stop receiving them when it transitions to `DISCONNECTED`.

| State          | Description                                                   |
| -------------- | ------------------------------------------------------------- |
| `CONNECTED`    | The subscription is actively connected and receiving updates. |
| `DISCONNECTED` | The subscription is not connected.                            |

#### Subscription Best Practices <a href="#subscription-best-practices" id="subscription-best-practices"></a>

* **Use unique subscription IDs.** If you call a subscribe method with the same ID twice, the second call will replace the first subscription.
* **Handle disconnections.** Monitor the `connectionStatusChanged` callback and re-subscribe if the connection is lost unexpectedly.
* **Unsubscribe when done.** Always unsubscribe when your component unmounts or the user navigates away to avoid memory leaks and unnecessary network activity.
* **Keep callbacks lightweight.** Subscription callbacks are invoked on the main thread. Perform heavy processing asynchronously to avoid blocking the UI.
* **Fetch full data on update.** For phone messages, the subscription notification is lightweight. Fetch the full resource via `getPhoneMessage` when you need the complete data payload.
