RxJS - .subscribe() vs .publish().connect()

前端 未结 2 1374
忘掉有多难
忘掉有多难 2020-12-25 14:21

This is mainly an RxJs best practice/approach question, since my POC code works but I\'m brand new to RxJs.

The question boils down to .subscribe() vs <

相关标签:
2条回答
  • 2020-12-25 14:39

    The difference between subscribe() and .publish().connect() is in when they subscribe to its source Observable. Consider the following Observable:

    let source = Observable.from([1, 2, 3])
    

    This Observable emits all values to an Observer right when it subscribes. So if I have two Observers then they receive all values in order:

    source.subscribe(val => console.log('obs1', val));
    source.subscribe(val => console.log('obs2', val));
    

    This will print to console:

    obs1 1
    obs1 2
    obs1 3
    obs2 1
    obs2 2
    obs2 3
    

    On the other hand calling .publish() returns a ConnectableObservable. This Observable doesn't subscribe to it's source (source in our example) in its constructor and only keeps its reference. Then you can subscribe multiple Observers to it and nothing happens. Finally, you call connect() and the ConnectableObservable subscribes to the source which starts emitting values. This time there're already two Observers subscribes so it emits values to both of them one by one:

    let connectable = source.publish();
    connectable.subscribe(val => console.log('obs1', val));
    connectable.subscribe(val => console.log('obs2', val));
    connectable.connect();
    

    Which prints to console:

    obs1 1
    obs2 1
    obs1 2
    obs2 2
    obs1 3
    obs2 3
    

    See live demo: http://plnkr.co/edit/ySWocRr99m1WXwsOGfjS?p=preview

    0 讨论(0)
  • 2020-12-25 14:39

    This sidesteps your question a bit but you may find it helpful:

    I would not return a different observable stream from the one that calls the http service because doing so makes it impossible for the calling function to:

    • cancel the stream
    • modify the stream
    • determine whether the operation was successful

    Instead I'd do:

    auth.servive.ts

    logout() : Observable<string>  {
           return this.http.get(...).map(this.extractData)          
                .catch(this.handleError);
    }
    

    Now the calling code can do whatever it wants with the resulting url

    logout.component.ts

    logout(){
        this.authService.logout().subscribe(
            url => window.location.href = url,
            err => {
                /*todo: handle if error was thrown by authService.handleError*/
            }
        );
    }
    
    0 讨论(0)
提交回复
热议问题