10

Trying to test new Android Room librarty with RxJava adapter. And I want to handle result if my query returns 0 objects from DB:

So here is DAO method:

@Query("SELECT * FROM auth_info")
fun getAuthInfo(): Flowable<AuthResponse>

And how I handle it:

        database.authDao().getAuthInfo()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .switchIfEmpty { Log.d(TAG, "IS EMPTY") }
            .firstOrError()
            .subscribe(
                    { authResponse -> Log.d(TAG, authResponse.token) },
                    { error -> Log.d(TAG, error.message) })

My DB is empty, so I expect .switchIfEmty() to work, but none of handling methods is firing. Neither .subscribe() nor .switchIfEmpty()

4

4 回答 4

14

Db Flowables 是可观察的(因此如果数据库发生更改,它们会继续调度),因此它永远不会完成。您可以尝试返回List<AuthResponse>。我们考虑过向后移植一个可选选项,但决定不这样做,至少现在是这样。相反,我们可能会在不同的已知库中添加对 Optional 的支持。

于 2017-05-27T19:09:03.883 回答
9

在 1.0.0-alpha5 版本中,room 添加了对 DAO 的支持MaybeSingle所以现在你可以编写类似的东西

@Query("SELECT * FROM auth_info")
fun getAuthInfo(): Maybe<AuthResponse>

你可以在这里阅读更多关于它的信息

于 2017-07-23T23:45:58.430 回答
0

您可以使用一些包装器来获取结果。例如:

public Single<QueryResult<Transaction>> getTransaction(long id) {
            return createSingle(() -> database.getTransactionDao().getTransaction(id))
                    .map(QueryResult::new);
}

    public class QueryResult<D> {
            public D data;
            public QueryResult() {}

            public QueryResult(D data) {
                this.data = data;
            }

            public boolean isEmpty(){
                return data != null;
            }
 }

protected <T> Single<T> createSingle(final Callable<T> func) {
            return Single.create(emitter -> {
                try {
                    T result = func.call();
                    emitter.onSuccess(result);

                } catch (Exception ex) {
                    Log.e("TAG", "Error of operation with db");
                }
            });
}

在这种情况下,像“Single”一样使用它,无论如何你都会得到结果。利用:

dbStorage.getTransaction(selectedCoin.getId())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(r -> {
                         if(!r.isEmpty()){
                           // we have some data from DB
                         } else {
                       }
                    })
于 2018-05-08T22:14:07.553 回答
0

switchIfEmpty将 a 作为参数Publisher<AuthResponse>。通过 SAM 转换,您给定的匿名函数将转换为此类。但是,它不遵循 a 预期的行为,Publisher因此它不会按预期工作。

用正确的实现替换它,Flowable.empty().doOnSubscribe { Log.d(TAG, "IS EMPTY") }它应该可以工作。

于 2017-05-27T11:03:47.900 回答