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 .publish().connect()
, since they both appear to do the same thing.
In my angular2 app, I have a button that calls a function to log the user out, which calls a function in my service that performs some server side actions and returns me a URL to redirect the user to. In order to initiate the request I call .subscribe()
to cause the observable to start producing values. I was reading an article on "Cold vs Hot Observables" and it another approach would be to call .publish().connect()
instead of .subscribe()
. Is there any benefit to either approach.
<a (click)="logout()">Logout</a>
The logout function looks like this:
logout.component.ts
logout() { this.authService.logout(); }
And the service (actual logout) looks like this:
auth.service.ts
logout() : Observable<boolean> {
this.http.get(this.location.prepareExternalUrl('api/v1/authentication/logout'))
.map(this.extractData)
.catch(this.handleError)
.do((x: string) => { window.location.href = x; })
.subscribe(); // Option A -
return Observable.of(true);
}
auth.service.alternative.ts
logout() : Observable<boolean> {
this.http.get(this.location.prepareExternalUrl('api/v1/authentication/logout'))
.map(this.extractData)
.catch(this.handleError)
.do((x: string) => { window.location.href = x; })
.publish() // Option B - Make connectable observable
.connect(); // Option B - Cause the connectable observable to subscribe and produce my value
return Observable.of(true);
}