如何从rxjava链中调用不可观察的代码

时间:2017-01-11 09:22:46

标签: java android sqlite rx-java

我在演示者中实现了一个rxjava调用链。 它的作用是如果没有从sqlite数据库返回的结果,则通过改进调用远程服务器。

然而,除了我们调用sqlite的存储库之外,一切都在使用rxjava。当sqlite返回结果时,它向我显示例如3个带有空值的结果。似乎从rxjava链调用不可观察的代码是行不通的?如果不使用StorIO或Brite,我怎么能这样做?

结果如下所示

https://www.gstatic.com/firebasejs/3.6.5/firebase.js:552:225

演示

@Override
protected void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    restartableLatestCache(REQUEST_ASSIGNMENTS,
        () -> mRepository.query()
                    .subscribeOn(Schedulers.io())
                    .observeOn(mainThread()),
        (assignmentActivity, response) -> assignmentActivity.onSuccess(response),
        (assignmentActivity, throwable) -> assignmentActivity.onError(throwable)
    );
}

存储库

return mAssignmentLocalDataStore.query(new AssignmentSpecification())
            .flatMap(assignments -> assignments == null || assignments.isEmpty() ?
                    mAssignmentRemoteDataStore.query()
                        .flatMap(remoteAssignments ->
                            Observable.zip(
                                    mEntityRepository.query()
                                            .flatMap(mEntityRepository::add),
                                    mFacilityRepository.query()
                                            .flatMap(mFacilityRepository::add),
                                    mAssignmentLocalDataStore.query(new AssignmentSpecification()),
                                    (remoteEntities, remoteFacilities, assignmentsRetry) -> assignmentsRetry
                            )
                        ): Observable.just(assignments)
            );

SQLite LocalDataStore

@Override
public Observable<List<Assignment>> query(Specification specification) {
    final SqlSpecification sqlSpecification = (SqlSpecification) specification;

    final SQLiteDatabase database = mOpenHelper.getReadableDatabase();
    final List<Assignment> assignments = new ArrayList<>();

    try {
        final Cursor cursor = database.rawQuery(sqlSpecification.toSqlQuery(), new String[]{});

        for (int i = 0, size = cursor.getCount(); i < size; i++) {
            cursor.moveToPosition(i);

            assignments.add(mToAssignmentMapper.map(cursor));
        }

        cursor.close();

        return Observable.just(assignments);

    } finally {
        database.close();
    }
}

1 个答案:

答案 0 :(得分:1)

-v更改为以下内容(使用query)。另一种变体是返回Observable.create并为每条记录调用Observable<Assignment>

subscriber.onNext