5

I have a function that needs to be called about every 500ms. The way I am looking at doing it with angular2 is using intervals and observables. I have tried this function to create the observable:

counter() { return Observable.create(observer => { setInterval(() => { return this.media.getCurrentPosition(); }, 500) }) } 

With this code for the subscriber:

test() { this.playerService.initUrl(xxxx) // This works this.playerService.counter().subscribe(data => { res => { console.log(data); } }) } 

I am very new to observables and angular2 so I might be taking the wrong approach completely. Any help is appreciated.

1 Answer 1

15

The Observable class has a static interval method taking milliseconds (like the setInterval method) as a parameter:

counter() { return Observable .interval(500) .flatMap(() => { return this.media.getCurrentPosition(); }); } 

And in your component or wherever:

test() { this.playerService.initUrl(xxxx) // This works this.playerService.counter().subscribe( data => { console.log(data); } ); } 
Sign up to request clarification or add additional context in comments.

4 Comments

This works perfectly, thanks! I did have to change the .flatmap() to .flatMap() to make it work correctly though.
just a note for others; Observable.interval is a static/class method, you cannot call it on an instance of Observable (I ran into an issue with this in angular when trying to repeat an http.get)
Observable.interval() is now deprecated not the preferred way of creating such an observable. The preferred way of doing this is via the IntervalObservable or TimerObservable. [ currently in Typscript 2.5.2, rxjs 5.4.3, Angular 5.0.0 ]
@Gokul do you have any sources for that?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.