简体   繁体   中英

How to use async pipe with RxJS interval on dynamically created component?

I was wondering if it's somehow possible to use async pipe with RxJS interval() on dynamically created components like in this example . Because if I apply async pipe inside of it, then when the components will change the interval will be mostly ignored.

Let's say I want to get data every 15 minutes but the components change every 15 seconds.

The only way I found is to take data from one Observable and save it to another one but I don't think that this is the best practice. Is there some other way on how to achieve this or this practice is ok?

The Observable looks like this:

interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl')));

Solution I found working:

interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl'))).subscribe((data) => {
  this.someUrlData = scheduled([data], asapScheduler);
});

The solution you have looks like it will work and is an acceptable way of doing it. If I were a new developer looking it over, though, I'd probably get confused about it and might attempt an ill-advised re-factor (unless you heavily commented it).

For that reason, I'd try a more readable approach (and forgive me if I'm misunderstanding your use case):

getData = new Subject<void>();

// UI Observable (referenced via the async pipe)
someData$ = this.getData.pipe(
    switchMap(() => this.http.get('someUrl')),
    shareReplay(1)
)

// Subscriptions (inside ngOnInit)
timer(0, 1000 * 60 * 15).subscribe(() => this.getData.next())

The advantage here is you also maintain control over when you get data. You could easily add a "refresh" button to the screen and have it just next on the getData subject.

Just be sure to clean up your subscription on the timer, otherwise it will go forever.


Update:

To answer your original question, it's 100% best practice to take a value from one Observable and save it to another one. To get around the component being destroyed, though, the best practice is to put this in a service, that way it stays intact.

i think the answer you found is the best way to reach what you want to do. you can make a shared state with the time of interval and when you create the dynamic component you check the interval and based on it make the http call I think in all ways you will need an outer state that you can listen to because you will destroy the interval every time you create the component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM