RxJS Subscriber unsubscribe vs. complete

前端 未结 2 1467
灰色年华
灰色年华 2021-01-08 01:11

I was reading through the RxJS docs and want to make sure I\'m understanding the difference between Subscriber.unsubscribe() and Subscriber.complete()

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-08 01:52

    Subscribers don't call complete(). You can call complete() on a Subject or more typically it's called for you "indirectly" using operators such as take(), takeWhile(), ...

    For example:

    const s = new Subject();
    const subscriber1 = s.subscribe(...);
    const subscriber2 = s.subscribe(...);
    s.complete(); // both subscribers will receive the complete notification
    
    // or with `take(1)` operator it'll call `complete()` for you
    const subscriber1 = s.take(1).subscribe(...);
    const subscriber2 = s.take(1).subscribe(...);
    s.next(42); // both subscribers will receive the complete notification
    

    Note that calling complete() on a Subject changes its inner state and there's no way to make it non-complete again while just unsubscribing a subscriber has no effect on the Subject.

    A little similar question: Observable Finally on Subscribe

提交回复
热议问题