Jon Sud
Jon Sud

Reputation: 11671

How to emit event manually to interval?

I have a interval timer from rxjs with withLatestFrom which I connect other observables for using them in my logic.

And I want to trigger event manually without waiting to the next interval to happens.

But the reload don't have next function. So is there a way to do it?

codesandbox.io

import { interval } from "rxjs";
import { tap, withLatestFrom } from "rxjs/operators";

console.clear();

const reload = interval(20 * 1000).pipe(
  /* withLatestFrom(someObs, ),*/
  tap(() => {
    console.log("do something");
  })
);

reload.subscribe(r => {

  console.log('nothing to do here');
});

Upvotes: 0

Views: 336

Answers (1)

Krantisinh
Krantisinh

Reputation: 1729

You can create one more observable say myEvent$ and fire your events whenever you want using it. Then merge the reload$ with myEvent$ and subscribe to the resultant observable.

import { Observable } from "rxjs";
import { tap, take, mergeWith } from "rxjs/operators";

const reload$ = interval(20 * 1000).pipe(
  /* withLatestFrom(someObs, ),*/
  tap(() => {
    console.log("do something");
  })
);

const myEvent$ = new Observable(sub => {
  sub.next("My new event");

  setTimeout(() => {
    sub.next("My another event after 3 seconds");
    sub.complete();
  }, 3000);
});

reload$.pipe(mergeWith(myEvent$)).subscribe(r => {
  console.log(r);
});

This way, you'll be in full control and will be able to fire your events whenever you want irrespective of when the reload$ fires and the same observer can subscribe to both the emissions.

Upvotes: 1

Related Questions