Reputation: 2374
Learning observable and Angular2. I want to find out the BEST practices of sharing an observable between multiple Angular2 components. As observable default is NOT multicast. So each subscription in different part of my app will open an new stream (call my API server again!). Also, I need to share the value and get the latest value of that observable. I hear people using behavior subject. But that is really confusing and I can not find a good example for that. Here is how I approach this in my authService:
userInfo$: Observable<User>;
this.userInfo$ = this.authInfo$
.switchMap(authInfo => this.findUserByuid(authInfo.$uid)) // finding user info base on authInfo turn or not.
.publishReplay(1).refCount();
And in my Angular2 component, I do this:
this.authService.userInfo$.subscribe(user => {
console.log (user);
this.user = user;
})
Everything works. But I wonder could I use behavior subject in this case? Am I doing everything right by sharing the userInfo$ among ALL my components (all my components which need userinfo$ will do the above code to subscribe to it)?
Upvotes: 4
Views: 1192
Reputation: 96891
Operator .publishReplay(1)
is just a shorthand for:
.multicast(new ReplaySubject(1))
If you want to use BehaviorSubject
you can use .publishBehavior('default')
which is a shorthand for.
.multicast(new BehaviorSubject('default'))
Since you're using multicasting already with .refCount()
you should be fine but it's hard to give any advice from what we can see here.
If you can or can't use BehaviorSubject
in your case depends on what you want to do. BehaviorSubject
takes as argument a default value that is emitted to its subscribers immediately when they subscribe. ReplaySubject
repeats a series of items from the source Observable that were emitted previously.
Upvotes: 5