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

com.stanfy.enroscar.async.internal.ObserverCallbacks 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 android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;

import com.stanfy.enroscar.async.Async;
import com.stanfy.enroscar.async.AsyncObserver;
import com.stanfy.enroscar.async.internal.OperatorBase.OperatorContext;
import com.stanfy.enroscar.async.internal.WrapAsyncLoader.Result;

/**
 * Loader callbacks based on {@link Async} and {@link AsyncObserver}.
 * @author Roman Mazur
 */
final class ObserverCallbacks implements LoaderManager.LoaderCallbacks> {

  /** Async provider (for lazy creation of Async in onCreateLoader). */
  private final AsyncProvider provider;

  /** Operator context. */
  private final OperatorContext operatorContext;

  /** Observer instance. */
  private final AsyncObserver observer;

  /** Whether to destroy loader when it is finished. */
  private final boolean destroyOnFinish;

  public ObserverCallbacks(final AsyncProvider asyncProvider,
                           final OperatorContext operatorContext,
                           final AsyncObserver observer,
                           final boolean destroyOnFinish) {
    this.provider = asyncProvider;
    this.operatorContext = operatorContext;
    this.observer = observer;
    this.destroyOnFinish = destroyOnFinish;
  }

  @Override
  public Loader> onCreateLoader(final int id, final Bundle args) {
    return new WrapAsyncLoader<>(new AsyncContext<>(
        operatorContext.context, provider.provideAsync()
    ));
  }

  @Override
  public void onLoadFinished(final Loader> loader, final Result result) {
    try {
      if (result.error != null) {
        observer.onError(result.error);
      } else {
        observer.onResult(result.data);
      }
    } finally {
      if (destroyOnFinish) {
        operatorContext.getLoaderManager().destroyLoader(loader.getId());
      }
    }
  }

  @Override
  public void onLoaderReset(final Loader> loader) {
    // nothing
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy