user3573738
user3573738

Reputation:

How to delay listen observer?

I have component that is activated by conditional show:

<app-list *ngIf="show"></app-list>

In place where I activate this component also I emit event:

this.tabsEvens.emitMoveToVersions(version);
this.router.navigate(["dictionary/versions/" + dict + '/' + code]);

Problem is, that I can no subscribe on this event in component app-list, because is is not created still, so therefore this does not work:

ngInit(){
   this._moveToVersionSub = this.tabEvents
    .listenMoveToVersions()
    .subscribe((parameters: any) => { // can not get parameters here });
}

How to catch even after sending emit and when component is built?

I have changed this lines:

this.router.navigate(["dictionary/versions/" + dict + '/' + code]);
this.tabsEvens.emitMoveToVersions(version);

And it works, first it activates component by route parameters, then emits event

Upvotes: 0

Views: 178

Answers (2)

J. S.
J. S.

Reputation: 2376

Your problem is you emit an even and afterwards listen on that stream. But of course the event has emitted before subscriber starts listening, so you won't get any value here.

You can use a BehaviorSubject instead of a normal Subject. BehaviorSubject always emit the last value to every new subscriber even if the event was emitted before subscriber starts listening.

Generally delaying an event to give every component the chance to start listening on the event stream is not a good idea in my opinion. Because you start guessing when resources finish initializing. But when something slows down the initializing progress it could break everything, better go for a clean solution.

EDIT Example:

tabEvents: Subject<any> = new Subject();

tabEvents.next('someevent')

this._moveToVersionSub = this.tabEvents
.listenMoveToVersions()
.subscribe((parameters: any) => { // nothing will happen here });

The same example with BehaviorSubject

tabEvents: BehaviorSubject<any> = new BehaviorSubject();

tabEvents.next('someevent')

this._moveToVersionSub = this.tabEvents
.listenMoveToVersions()
.subscribe((parameters: any) => { // parameters = 'someevent });

There is no difference in implementing these two solutions. Only difference is that with a BehaviorSubject the subscribe will be triggered with 'someevent' because BehaviorSubject emits this event to every new subscriber which subscribes after the value has emitted.

Upvotes: 1

KLTR
KLTR

Reputation: 1334

You should use delay .

as the following :

example.pipe(
delay(2000)
subscribe( ...)
)

you can learn more : https://www.learnrxjs.io/operators/utility/delay.html

Upvotes: 0

Related Questions