All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.contentful.java.cda.CDACallback Maven / Gradle / Ivy

There is a newer version: 9.1.0
Show newest version
package com.contentful.java.cda;

import rx.Subscription;

/**
 * Communicates responses from a server or offline requests. One and only one method will be
 * invoked in response to a given request.
 * @param  expected response type.
 */
public abstract class CDACallback {
  private final Object LOCK = new Object();

  private boolean cancelled;

  private Subscription subscription;

  /** Successful response. */
  protected abstract void onSuccess(T result);

  /** Invoked when a network or unexpected exception occurred during the HTTP request. */
  protected void onFailure(Throwable error) {
  }

  /** Returns true in case {@link #cancel()} was called. */
  public boolean isCancelled() {
    synchronized (LOCK) {
      return cancelled;
    }
  }

  /**
   * Cancels the subscription for this callback, onFailure()/onSuccess() methods will not be
   * called.
   */
  public void cancel() {
    synchronized (LOCK) {
      cancelled = true;
      unsubscribe();
    }
  }

  void setSubscription(Subscription subscription) {
    synchronized (LOCK) {
      this.subscription = subscription;
    }
  }

  void unsubscribe() {
    synchronized (LOCK) {
      if (subscription != null) {
        subscription.unsubscribe();
        subscription = null;
      }
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy