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

com.stanfy.enroscar.async.internal.ObserverBuilder Maven / Gradle / Ivy

Go to download

Helper classes and extended abstractions for Android loaders, content resolvers, and DB access.

There is a newer version: 2.1
Show newest version
package com.stanfy.enroscar.async.internal;

import com.stanfy.enroscar.async.Action;
import com.stanfy.enroscar.async.AsyncError;
import com.stanfy.enroscar.async.AsyncObserver;

/**
 * @author Roman Mazur - Stanfy (http://stanfy.com)
 */
public final class ObserverBuilder {

  /** Building target. */
  private final T description;

  /** Observer instance. */
  private final Observer observer = new Observer<>();

  public ObserverBuilder(final int loaderId, final T description) {
    this.description = description;
    this.description.addObserver(loaderId, observer);
  }

  public ObserverBuilder doOnResult(final Action resultAction) {
    observer.resultAction = resultAction;
    return this;
  }

  public ObserverBuilder doOnError(final Action errorAction) {
    observer.errorAction = errorAction;
    return this;
  }

  public T alsoWhen() {
    return description;
  }

  /**
   * {@link AsyncObserver} based on {@link Action}s.
   * @param  data type
   */
  private static class Observer implements AsyncObserver {

    /** On result. */
    Action resultAction;
    /** On error. */
    Action errorAction;

    @Override
    public void onError(final Throwable e) {
      if (errorAction != null) {
        errorAction.act(e);
      } else {
        throw new AsyncError(e);
      }
    }

    @Override
    public void onResult(final D data) {
      if (resultAction != null) {
        resultAction.act(data);
      }
    }

  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy