简体   繁体   English

RxJava:使用Builder对象链接Observables

[英]RxJava: Chaining Observables w/ Builder object

I'm using a Builder pattern to build upon a model object which combines data from different network calls and I'm having a hard time understanding the best way to take the model object from the first network call and combine the data from the second network call into the original model object. 我正在使用Builder模式构建一个模型对象,该模型对象组合了来自不同网络调用的数据,我很难理解从第一个网络调用中获取模型对象的最佳方法,并结合来自第二个网络的数据调用原始模型对象。

My actual subscription: 我的实际订阅:

myFirstApiRepository.getFirstModelObjectBuilder()
    .flatmap(firstModelObjectBuilder -> mySecondApiRepository.getSomeExtraData(firstModelObjectBuilder))
    .observable.subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(getMySubscriber());

First network call: 第一次网络通话:

public Observable<FirstModelObject.Builder> getFirstModelObjectBuilder() {
    return myFirstApiResource.getSomeData(...)
            .flatMap(someData -> Observable.just(new FirstModelObject.Builder()
                .setFirstAttribute(someData.getFirstAttribute())
                .setSecondAttribute(someData.getSecondAttribute())));
}

Second network call: 第二次网络通话:

public Observable<FirstModelObject> getSomeExtraData(FirstModelObject.Builder builder) {
    return mySecondApiResource.getSomeData(...)
        .flatMap(aString -> builder.setSomeStringValue(aString)
                                   .build());
}

The problem here is that I have to pass the builder object into the second network call's observable. 这里的问题是我必须将构建器对象传递给第二个网络调用的可观察对象。 This makes it very rigid and I'd rather not have my SecondApiRepository rely on and reference a data type which it shouldn't need to reference. 这使得它非常严格,我宁愿不让我的SecondApiRepository依赖并引用它不应该引用的数据类型。 It also makes this second method here " .build() " the object, which is not good. 它还使第二种方法在这里成为“ .build() ”对象,这是不好的。 So, how can I use the firstModelObject and add data to it from the second network call in a clean way ? 那么,我如何使用firstModelObject并以干净的方式从第二次网络调用中firstModelObject添加数据

If this is just bad design, please let me know. 如果这只是糟糕的设计,请告诉我。 I'm still trying to learn more about RxJava best practices. 我仍在尝试了解有关RxJava最佳实践的更多信息。 :) :)

If your second request relies on first request's result, then check my answer - https://stackoverflow.com/a/41820372/7045114 . 如果您的第二个请求依赖于第一个请求的结果,请检查我的答案 - https://stackoverflow.com/a/41820372/7045114

If not - just use zip operator: 如果不是 - 只需使用zip操作符:

Combines the emissions of multiple Observables together via a specified function and emit single items for each combination based on the results of this function. 通过指定的功能将多个Observable的排放组合在一起,并根据此功能的结果为每个组合发出单个项目。

Observable.zip(firstRequest, secondRequest, (firstResult, secondResult) -> {
    //process results
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM