Checking the Subscription Status of a Topic

You might want to check if the current user is already subscribed to a topic. For example, your application may want to show a "SUBSCRIBE" button for users who have not yet subscribed to a topic and an "UNSUBSCRIBE" button instead for those users who are already subscribed to the topic.

Here is the sample code for checking the subscription status.

  • try {
      // Instantiate the target topic.
      String topicName = "SendingAlert";
      KiiTopic topic = Kii.topic(topicName);
    
      // Check if the current user is subscribed to the topic.
      KiiUser user = KiiUser.getCurrentUser();
      KiiPushSubscription sub = user.pushSubscription();
      boolean isSubscribed = sub.isSubscribed(topic);
    
      if (isSubscribed) {
        // The current user is subscribed to the topic.
      } else {
        // The current user is not subscribed to the topic.
      }
    } catch (IOException ioe) {
      // Handle the error.
    } catch (AppException e) {
      // Handle the error.
    }
  • // Instantiate the target topic.
    String topicName = "SendingAlert";
    KiiTopic topic = Kii.topic(topicName);
    
    // Check if the current user is subscribed to the topic.
    KiiUser user = KiiUser.getCurrentUser();
    KiiPushSubscription sub = user.pushSubscription();
    sub.isSubscribed(topic, new KiiPushCallBack() {
      @Override
      public void onCheckSubscriptionCompleted(int taskId, KiiSubscribable target, boolean isSubscribed, Exception exception) {
        if (exception != null) {
          // Handle the error.
          return;
        }
    
        if (isSubscribed) {
          // The current user is subscribed to the topic.
        } else {
          // The current user is not subscribed to the topic.
        }
      }
    });

Here's a description of the sample code:

  • Instantiates a topic.
  • Creates a KiiPushSubscription instance by calling the pushSubscription method.
  • Calls the isSubscribed method to check if the current user is already subscribed to the topic.