Search in sources :

Example 1 with Query

use of com.squareup.sqlbrite.SqlBrite.Query in project sqlbrite by square.

the class SqlBriteTest method asRowsEmptyWhenNullCursor.

@Test
public void asRowsEmptyWhenNullCursor() {
    Query nully = new Query() {

        @Nullable
        @Override
        public Cursor run() {
            return null;
        }
    };
    TestSubscriber<Name> subscriber = new TestSubscriber<>();
    final AtomicInteger count = new AtomicInteger();
    nully.asRows(new Func1<Cursor, Name>() {

        @Override
        public Name call(Cursor cursor) {
            count.incrementAndGet();
            return Name.MAP.call(cursor);
        }
    }).subscribe(subscriber);
    subscriber.assertNoValues();
    subscriber.assertCompleted();
    assertThat(count.get()).isEqualTo(0);
}
Also used : Query(com.squareup.sqlbrite.SqlBrite.Query) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestSubscriber(rx.observers.TestSubscriber) Func1(rx.functions.Func1) MatrixCursor(android.database.MatrixCursor) Cursor(android.database.Cursor) Test(org.junit.Test)

Example 2 with Query

use of com.squareup.sqlbrite.SqlBrite.Query in project sqlbrite by square.

the class BriteContentResolver method createQuery.

/**
   * Create an observable which will notify subscribers with a {@linkplain Query query} for
   * execution. Subscribers are responsible for <b>always</b> closing {@link Cursor} instance
   * returned from the {@link Query}.
   * <p>
   * Subscribers will receive an immediate notification for initial data as well as subsequent
   * notifications for when the supplied {@code uri}'s data changes. Unsubscribe when you no longer
   * want updates to a query.
   * <p>
   * Since content resolver triggers are inherently asynchronous, items emitted from the returned
   * observable use the {@link Scheduler} supplied to {@link SqlBrite#wrapContentProvider}. For
   * consistency, the immediate notification sent on subscribe also uses this scheduler. As such,
   * calling {@link Observable#subscribeOn subscribeOn} on the returned observable has no effect.
   * <p>
   * Note: To skip the immediate notification and only receive subsequent notifications when data
   * has changed call {@code skip(1)} on the returned observable.
   * <p>
   * <b>Warning:</b> this method does not perform the query! Only by subscribing to the returned
   * {@link Observable} will the operation occur.
   *
   * @see ContentResolver#query(Uri, String[], String, String[], String)
   * @see ContentResolver#registerContentObserver(Uri, boolean, ContentObserver)
   */
@CheckResult
@NonNull
public QueryObservable createQuery(@NonNull final Uri uri, @Nullable final String[] projection, @Nullable final String selection, @Nullable final String[] selectionArgs, @Nullable final String sortOrder, final boolean notifyForDescendents) {
    final Query query = new Query() {

        @Override
        public Cursor run() {
            long startNanos = nanoTime();
            Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
            if (logging) {
                long tookMillis = NANOSECONDS.toMillis(nanoTime() - startNanos);
                log("QUERY (%sms)\n  uri: %s\n  projection: %s\n  selection: %s\n  selectionArgs: %s\n  " + "sortOrder: %s\n  notifyForDescendents: %s", tookMillis, uri, Arrays.toString(projection), selection, Arrays.toString(selectionArgs), sortOrder, notifyForDescendents);
            }
            return cursor;
        }
    };
    OnSubscribe<Query> subscribe = new OnSubscribe<Query>() {

        @Override
        public void call(final Subscriber<? super Query> subscriber) {
            final ContentObserver observer = new ContentObserver(contentObserverHandler) {

                @Override
                public void onChange(boolean selfChange) {
                    subscriber.onNext(query);
                }
            };
            contentResolver.registerContentObserver(uri, notifyForDescendents, observer);
            subscriber.add(Subscriptions.create(new Action0() {

                @Override
                public void call() {
                    contentResolver.unregisterContentObserver(observer);
                }
            }));
            // Trigger initial query.
            subscriber.onNext(query);
        }
    };
    final Observable<Query> queryObservable = //
    Observable.create(subscribe).onBackpressureLatest().observeOn(//
    scheduler).compose(// Apply the user's query transformer.
    queryTransformer).onBackpressureLatest();
    // TODO switch to .to() when non-@Experimental
    return new QueryObservable(new OnSubscribe<Query>() {

        @Override
        public void call(Subscriber<? super Query> subscriber) {
            queryObservable.unsafeSubscribe(subscriber);
        }
    });
}
Also used : Action0(rx.functions.Action0) Query(com.squareup.sqlbrite.SqlBrite.Query) Subscriber(rx.Subscriber) OnSubscribe(rx.Observable.OnSubscribe) Cursor(android.database.Cursor) ContentObserver(android.database.ContentObserver) CheckResult(android.support.annotation.CheckResult) NonNull(android.support.annotation.NonNull)

Example 3 with Query

use of com.squareup.sqlbrite.SqlBrite.Query in project sqlbrite by square.

the class QueryTest method mapToListIgnoresNullCursor.

@Test
public void mapToListIgnoresNullCursor() {
    Query nully = new Query() {

        @Nullable
        @Override
        public Cursor run() {
            return null;
        }
    };
    TestSubscriber<List<Employee>> subscriber = new TestSubscriber<>();
    Observable.just(nully).lift(Query.mapToList(Employee.MAPPER)).subscribe(subscriber);
    subscriber.assertNoValues();
    subscriber.assertCompleted();
}
Also used : Query(com.squareup.sqlbrite.SqlBrite.Query) TestSubscriber(rx.observers.TestSubscriber) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Example 4 with Query

use of com.squareup.sqlbrite.SqlBrite.Query in project sqlbrite by square.

the class QueryTest method mapToOneOrDefaultReturnsDefaultWhenNullCursor.

@Test
public void mapToOneOrDefaultReturnsDefaultWhenNullCursor() {
    Employee defaultEmployee = new Employee("bob", "Bob Bobberson");
    Query nully = new Query() {

        @Nullable
        @Override
        public Cursor run() {
            return null;
        }
    };
    TestSubscriber<Employee> subscriber = new TestSubscriber<>();
    Observable.just(nully).lift(Query.mapToOneOrDefault(Employee.MAPPER, defaultEmployee)).subscribe(subscriber);
    subscriber.assertValues(defaultEmployee);
    subscriber.assertCompleted();
}
Also used : Employee(com.squareup.sqlbrite.TestDb.Employee) Query(com.squareup.sqlbrite.SqlBrite.Query) TestSubscriber(rx.observers.TestSubscriber) Test(org.junit.Test)

Example 5 with Query

use of com.squareup.sqlbrite.SqlBrite.Query in project sqlbrite by square.

the class BriteDatabaseTest method queryCreatedBeforeTransactionButSubscribedAfter.

@Test
public void queryCreatedBeforeTransactionButSubscribedAfter() {
    Observable<Query> query = db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES);
    Transaction transaction = db.newTransaction();
    try {
        db.insert(TABLE_EMPLOYEE, employee("john", "John Johnson"));
        db.insert(TABLE_EMPLOYEE, employee("nick", "Nick Nickers"));
        transaction.markSuccessful();
    } finally {
        transaction.end();
    }
    query.subscribe(o);
    o.assertCursor().hasRow("alice", "Alice Allison").hasRow("bob", "Bob Bobberson").hasRow("eve", "Eve Evenson").hasRow("john", "John Johnson").hasRow("nick", "Nick Nickers").isExhausted();
}
Also used : Query(com.squareup.sqlbrite.SqlBrite.Query) Transaction(com.squareup.sqlbrite.BriteDatabase.Transaction) Test(org.junit.Test)

Aggregations

Query (com.squareup.sqlbrite.SqlBrite.Query)12 Test (org.junit.Test)10 Cursor (android.database.Cursor)5 MatrixCursor (android.database.MatrixCursor)5 TestSubscriber (rx.observers.TestSubscriber)5 Func1 (rx.functions.Func1)3 Transaction (com.squareup.sqlbrite.BriteDatabase.Transaction)2 Employee (com.squareup.sqlbrite.TestDb.Employee)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 ContentObserver (android.database.ContentObserver)1 CheckResult (android.support.annotation.CheckResult)1 NonNull (android.support.annotation.NonNull)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 OnSubscribe (rx.Observable.OnSubscribe)1 Subscriber (rx.Subscriber)1 Action0 (rx.functions.Action0)1 Action1 (rx.functions.Action1)1 Func2 (rx.functions.Func2)1 CompositeSubscription (rx.subscriptions.CompositeSubscription)1