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

com.activeandroid.sqlbrite.QueryToListOperator Maven / Gradle / Ivy

There is a newer version: 3.1.5
Show newest version
package com.activeandroid.sqlbrite;

import android.database.Cursor;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.exceptions.Exceptions;
import rx.exceptions.OnErrorThrowable;
import rx.functions.Func1;

final class QueryToListOperator implements Observable.Operator, SqlBrite.Query> {
  private final Func1 mapper;

  QueryToListOperator(Func1 mapper) {
    this.mapper = mapper;
  }

  @Override
  public Subscriber call(final Subscriber> subscriber) {
    return new Subscriber(subscriber) {
      @Override public void onNext(SqlBrite.Query query) {
        try {
          Cursor cursor = query.run();
          List items = new ArrayList<>(cursor.getCount());
          try {
            for (int i = 1; cursor.moveToNext() && !subscriber.isUnsubscribed(); i++) {
              T item = mapper.call(cursor);
              if (item == null) {
                throw new NullPointerException("Mapper returned null for row " + i);
              }
              items.add(item);
            }
          } finally {
            cursor.close();
          }
          if (!subscriber.isUnsubscribed()) {
            subscriber.onNext(items);
          }
        } catch (Throwable e) {
          Exceptions.throwIfFatal(e);
          onError(OnErrorThrowable.addValueAsLastCause(e, query.toString()));
        }
      }

      @Override public void onCompleted() {
        subscriber.onCompleted();
      }

      @Override public void onError(Throwable e) {
        subscriber.onError(e);
      }
    };
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy