如何创建订阅可观察对象的BehaviorSubject?

时间:2017-07-06 05:37:48

标签: java android retrofit rx-java reactivex

我有一个应该返回BehaviorSubject的函数。该主题旨在返回Profile

的最新版本

(用户)Profile只是一个POJO,其中包含对三个成员的引用:
- User
- 该用户MeasurementList
- 和Deadline

其中两个属性是通过改装调用获得的,其中一个已经保存在类变量中。

只要observable发出新的measurement listdeadline,BehaviorSubject就会发出新的更新的个人资料。

这是应该发生什么的(希望是有帮助的)图表 enter image description here

这是我到目前为止所拥有的

 public BehaviorSubject<Profile> observeProfile() {

        if (profileBS == null) {

            profileBS = BehaviorSubject.create();

            Observable o = Observable.combineLatest(
                    Observable.just(userAccount),
                    observeMeasurements(),
                    observeDeadline(),
                    Profile::new
            );


            profileBS.subscribeTo(o); //subscribeTo does not exist, but this is what I am trying to figure out how to do.

        }
        return profileBS;
    }

有人可以帮我正确创建这个BehaviorSubject吗?

感谢。

2 个答案:

答案 0 :(得分:2)

Subject实现了Observer接口,因此您可以执行以下操作

public BehaviorSubject<Profile> observeProfile() {

        if (profileBS == null) {

            profileBS = BehaviorSubject.create();

            Observable o = Observable.combineLatest(
                    Observable.just(userAccount),
                    observeMeasurements(),
                    observeDeadline(),
                    Profile::new
            );

            // Note the following returns a subscription. If you want to prevent leaks you need some way of unsubscribing.
            o.subscribe(profileBS); 

        }
        return profileBS;
}

请注意,您应该想出一种处理结果订阅的方法。

答案 1 :(得分:0)

我想我和你面临着同样的问题。在我回答之前,我想讲一些历史。 所以我想很多人都看到了JakeWharton在Devoxx上发表的演讲:The State of Managing State with RxJava

所以他提出了一个基于一些变形金刚的架构。但问题是即使是那些Transformer实例也会在ViewObservables之外生存。每次ViewObservable使用它们时,它们仍会创建新的Observable。这是因为运营商的概念。

因此,对此的一个常见解决方案是使用主题作为您在问题中所做的网关。但是新问题是你过早订阅你的来源。

订阅操作应在subscribeActual()中完成,这将由您的下游由subscribe()方法触发。但是您在中间订阅了您的上游。你输了你的比赛。 我通过解决这个问题而苦苦挣扎但从未找到解决方案。

但最近感谢Davik的回答:RxJava - .doAfterSubscribe()? 我想出了类似的东西:

public BehaviorSubject<Profile> observeProfile() {
    public Observable resultObservable;
    if (profileBS == null) {

        profileBS = BehaviorSubject.create();
        //this source observable should save as a field as well 
        o = Observable.combineLatest(
                Observable.just(userAccount),
                observeMeasurements(),
                observeDeadline(),
                Profile::new
        );
        //return this observable instead of your subject
        resultObservable = profileBS.mergeWith(
            Observable.empty()
                      .doOnComplete(() -> {
                          o.subscribe(profileBS);
                      }))
    } return resultObservable;
}

诀窍是。您使用此approche来创建像doAfterSubscribe这样的运算符。因此,只有下游已订阅您的主题。您的主题将订阅您原来的上游来源。

希望这可以提供帮助。抱歉我的英语不好。

相关问题