Subscribing to a Bucket

A user who is interested in changes to a certain bucket can receive a push notification when a change occurs in the bucket by subscribing to the bucket.

Here is the sample code for subscribing to a bucket.

  • // If the bucket is new, save it on Kii Cloud by saving a KiiObject in the bucket and then
    // subscribe to the bucket. You cannot subscribe to a bucket if it does not exist on Kii Cloud.
    
    // Instantiate a bucket.
    KiiUser user = KiiUser.getCurrentUser();
    KiiBucket bucket = user.bucket("_target_bucket_");
    
    try {
      // Create and save a KiiObject in the bucket.
      bucket.object().save();
    
      // Subscribe to the bucket.
      user.pushSubscription().subscribeBucket(bucket);
    } catch (IOException e) {
      // Handle the error.
    } catch (AppException e) {
      // Handle the error.
    }
  • // If the bucket is new, save it on Kii Cloud by saving a KiiObject in the bucket and then
    // subscribe to the bucket. You cannot subscribe to a bucket if it does not exist on Kii Cloud.
    
    // Instantiate a bucket.
    KiiUser user = KiiUser.getCurrentUser();
    final KiiBucket bucket = user.bucket("_target_bucket_");
    
    // Create and save a KiiObject in the bucket.
    bucket.object().save(new KiiObjectCallBack() {
      @Override
      public void onSaveCompleted(int token, KiiObject object, Exception exception) {
        if (exception != null) {
          // Handle the error.
          return;
        }
    
        // Subscribe to the bucket.
        user.pushSubscription().subscribeBucket(bucket, new KiiPushCallBack() {
          @Override
          public void onSubscribeBucketCompleted(int taskId, KiiBucket target, Exception exception) {
            if (exception != null) {
              // Handle the error.
              return;
            }
          }
        });
      }
    });

Subscribing to a bucket with many KiiObjects

A "Push to App" notification will be launched every time there is an update event in the target bucket. Subscribing to a bucket with many Objects, therefore, might cause some issues.

For example, let us assume that a user having three devices is subscribing to a bucket. This bucket has 100 Objects inside. If all of them are updated, it will trigger 100 push notifications per device or 300 total push notifications for this user.

One way to cope with such a situation (massive amount of push notifications triggered) is to use the Push to User Notification instead of the "Push to App" notifications. By sending a push request to a topic after the object updates are done, you can just send one "push to user" message per device. A shortcoming of this method is that there will be a time gap between the object updates and the push notification delivery, and this gap might cause some notifications to be dropped (See Transactions for the related discussion).