Warm tip: This article is reproduced from serverfault.com, please click

Subcribed Oberservable: fire manually possible?

发布于 2020-12-01 11:51:51

I have an Oberservable for getting data.

I use a Subscription to call it in an interval in my component.

ngOnInit () {

this.subscr = interval (10000).pipe (
  startWith (0),
  mergeMap (obs => this.myservice.getData ().pipe (catchError (error =>
  {
    // error
  })))).subscribe (resp =>
  {
    // data
  });
}

ngOnDestroy ()
{
  this.subscr.unsubscribe ();
}

I like to have the data refreshed by action (e.g. a button).

refreshNow ()
{
  this.myservice.getData ().pipe (catchError (error =>
  {
    // error
  })))).subscribe (resp =>
  {
    // data
  });
}

But I do not like to have getData multiple times in the code. Is there a way I can fire this.subscr manually??

Questioner
chris01
Viewed
0
distante 2020-12-01 20:21:38

You can use a Subject and combine the both with merge(), something like:

private readonly triggerRefresh$$ = new Subject<void>();

// ....

this.subscr = merge(interval(10000), this.triggerRefresh$$)
    .pipe (
        switchMapTo(this.myservice.getData ()
            .pipe(catchError (error => {}))
        )
    ).subscribe (resp => {
        // data
      });


refreshNow () {
   this.triggerRefresh$$.next();
}