如何在RxJava流中缓存记录并稍后在同一流中使用记录?

时间:2019-02-23 19:45:45

标签: rx-java2

我正在研究在当前的Android应用程序中使用RxJava

我有以下用例,看不到如何在RxJava中实现它。

1). Read a set of database records as a Single<List<DBRecord>>
2). Transform each database record to an associated network model class
3). Call a remote Update API for each network object
4). When the remote Update API call is successful, update the specific database record.

到目前为止,我的代码是

    login().andThen(DatabaseController.fetchDBRecord())
        .toObservable()
        .flatMapIterable(dbRecord -> dbRecord)
        .flatMapSingle(database -> transformDatabase(database, DB_RECORD_MAPPER))
        .flatMapSingle(NetworkController::UpdateCall)
        .flatMapCompletable(response -> DatabaseController.updateDBRecord(response.body()))

我遇到的问题是Update API响应是一个字符串值,其中包含“ SUCCESS”或“ FAILURE”,例如该响应无法识别当前的DBRecord详细信息。

执行.flatMapIterable(dbRecord -> dbRecord)时,有什么方法可以从.flatMapCompletable(response -> DatabaseController.updateDBRecord(response.body()))阶段访问dbRecord

这样我就可以将dbRecord传递到DatabaseController.updateDBRecord(dbRecord)中了……

login().andThen(DatabaseController.fetchDBRecord())
            .toObservable()
            .flatMapIterable(dbRecord -> dbRecord)
            .flatMapSingle(database -> transformDatabase(database, DB_RECORD_MAPPER))
            .flatMapSingle(NetworkController::UpdateCall)
            .flatMapCompletable(response -> DatabaseController.updateDBRecord(dbRecord))

已更新

我已经意识到用例比最初说明的要复杂:

1). Read a set of database records as a Single<List<DBRecord>>
2). Transform each database record to an associated network model class
3). Call a remote Update API for each network object
4). Only when the remote Update API call is successful, update the specific database record.

如果我使用的是嵌套流,我如何知道嵌套的API调用在我的后续外部流中成功返回,以更新数据库?

login().andThen(DatabaseController.fetchDBRecord())
    .flattenAsObservable(dbRecord -> dbRecord)
    .flatMapCompletable(database -> transformDatabase(database, DB_RECORD_MAPPER)
            .flatMap(NetworkController::UpdateCall)
            .flatMapCompletable(response -> DatabaseController.updateDBRecord(database)))

1 个答案:

答案 0 :(得分:1)

您可以使用嵌套流。例如:

--allow-empty