chris01
chris01

Reputation: 12311

Angular: trigger a interval observable

How can I trigger an interval-observable to perform its action outside the defined interval but keep the interval running as defined?

Sample:

Intervall is 10s. I like to call doit not only in the intervall but also if an event occours - lets say a button-click.

Sure I can call doit in the button-handler but is there a way I can do it with the obervable (e.g. sort of obs.trigger ())??

export class MyComponent implements OnInit
{
    private obs : any;   // the observable instance

    ngOnInit ()
    {
        this.obs = Observable.interval (10 * 1000)
            .startWith (0)
            .subscribe ((n) => 
            {
                doit ();
            });
    }

    doit ()
    {
       // some action
    }

    clicked ()
    {
        doit ();   // works but I am looking for a way to do it with obs
    }
}

Thanks!

Upvotes: 0

Views: 1811

Answers (3)

chris01
chris01

Reputation: 12311

I see if I just perform

clicked ()
{
  this.obs.next ();
}

it is working as I expect.

Is there a negative impact I do not see? Because your answers are slightly more complex and I am afraid I miss something?

Upvotes: -1

LLai
LLai

Reputation: 13396

You could use the merge operator to combine two observables. Your interval plus a fromEvent click observable.

Observable.merge(
    Observable.interval(10 * 1000),
    Observable.fromEvent(this.myButton.nativeElement, 'click')
)
.startWith(0)
.subscribe(...)

Here is a stackblitz demoing this.

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176886

I dont think that is possible as , you create observable based on interval .

But if you want observable than you can create it like this

<button (click)="obs.next($event)">

private obs = new Subject();
public obs$ = this.obs.asObservable();

and than just combine observable like this

first.concat(second).subscribe(res => console.log(res));

So I am suggesting create two oberservable and than combine them. you already have one and create one more for button click and than combine them.


<button (click)="obs.next($event)">

private obsButtonClick = new Subject();
public obs$ = this.obsButtonClick.asObservable();

ngOnInit ()
{
    this.obs = Observable.interval (10 * 1000)
        .startWith (0);

     this.obs.concat(obsButtonClick).subscribe ((n) => 
        {
            doit ();
        });
}

Upvotes: 3

Related Questions