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

com.stanfy.enroscar.async.internal.BaseAsync 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.Async;
import com.stanfy.enroscar.async.AsyncObserver;

import java.util.ArrayList;

/**
 * Base implementation for {@link com.stanfy.enroscar.async.Async}.
 * Supports multiple observers. Not thread safe.
 * @param  data type
 * @author Roman Mazur - Stanfy (http://stanfy.com)
 */
class BaseAsync implements Async {

  /** Observers collection. */
  private final ArrayList> observers = new ArrayList<>(3);

  @Override
  public final void subscribe(final AsyncObserver observer) {
    observers.add(observer);
    if (observers.size() == 1) {
      onTrigger();
    }
  }

  @Override
  public final void cancel() {
    observers.clear();
    onCancel();
  }

  protected void onTrigger() {
    // nothing
  }

  protected final void postResult(final D data) {
    int count = observers.size();
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < count; i++) {
      observers.get(i).onResult(data);
    }
  }

  protected final void postError(final Throwable error) {
    int count = observers.size();
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < count; i++) {
      observers.get(i).onError(error);
    }
  }

  /**
   * Invoked when async operation is canceled.
   */
  protected void onCancel() {
    // nothing
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy