使用订阅者订阅/取消订阅多个订阅

时间:2017-12-25 06:03:17

标签: rx-java

我无法找到RxJava Subscriber如何处理多个Subscription的明确解释。 (评论参考RxJava 1.x)

Subscriber有一个add( Subscription )方法,"将Subscription添加到Subscriber的{​​{1}} s&#列表中34;,没有进一步解释。 Subscription可能参与的规则是什么?

有趣的是,SubscriptionSubscriber都有Subscription方法。据推测,unsubscribe()会取消订阅整个subscriber.unsubscribe()列表,而Subscription只会取消该subscription.unsubscribe(),但我无法在任何地方找到此说明。它是否正确?

我还没潜入RxJava 2.x;是否有任何更改(Subscription被重命名为Subscription除外)?

2 个答案:

答案 0 :(得分:0)

为此提供一些启示,并更好地了解我制作此示例的订阅者和订阅

/**
 * In every moment we have the possibility to create our own subscriber, which you have to implement ActionSubscriber
 *  with onNext, onError and onComplete functions.
 *  Once that you do that you can attach that subscriber into a subscription.
 *  
 *  You can also can add the subscription into a subscriptionList that a subscriber has to know the state of the
 *  subscriptions where he is part of
 */
@Test
public void subscriberAndSubscription() {
    Integer[] numbers = {0, 1, 2};

    Subscriber subscriber = new ActionSubscriber(number -> {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Subscriber number:" + number);
    },
            System.out::println,
            () -> System.out.println("Subscriber End of pipeline"));

    Subscription subscription = Observable.from(numbers).subscribeOn(Schedulers.newThread()).subscribe(subscriber);
    Subscription subscription1 = Observable.from(numbers).subscribeOn(Schedulers.newThread()).subscribe(subscriber);

    subscriber.add(subscription);
    subscriber.add(subscription1);
    System.out.println("Is Unsubscribed??:" + subscriber.isUnsubscribed());


    new TestSubscriber((Observer) subscription)
            .awaitTerminalEvent(5, TimeUnit.SECONDS);

    System.out.println("Is Unsubscribed??:" + subscriber.isUnsubscribed());

}

据我所知,subscriber.add(subscription);是一种机制,用于控制订阅者所在的订阅数量以及这些订阅的状态。所以我可以知道我的所有订阅何时完成发布和取消订阅我。

我在这里做了一些例子https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/creating/ObservableSubscription.java

答案 1 :(得分:0)

RxJava 1在内部使用

Subscriber.add()来关联资源,例如Scheduler.Worker s,其他Subscriber以及Subscriber时必须取消订阅/执行的操作取消订阅或完成。

Subscriber.unsubscribe()因为Subscriber也是Subscription,它允许将它们链接在一起并相互添加以用于上述清理例程。

在内部,Subscriber有一个Subscription列表,可以一起取消订阅。

作为RxJava API的最终使用者,您不必担心add()。但是,将此资源容器逻辑暴露给公众并使其加载所有Subscriber并不是理想的解决方案。 2.x已将架构更改为overcome this property

在2.x中,Disposable接口扮演Subscription接口的角色,但默认Observer不再承载资源。这样做是上游的责任。但是,为了支持旧的资源容器行为,引入了单独的抽象类ResourceObserver