I'm new to the whole Rx thing and reactive programming, however I have to deal with such a situation. I want a interval observable to check a hardware's status by a POST request to its REST API every 500ms to see if the response changes. So once it changes, I want such interval observable POST request shut down immediately, leaving resource to other future operations. Here is a piece of code.
myLoop(item_array:number[], otheroption : string){
for (let item of item_array){
//set hardware option, still a request
this.configHardware(item,otheroption)
//after config the hardware, command hardware take action
.flatMap(() => {
//this return a session id for check status
this.takeHardwareAction()
.flatMap( (result_id) => {
//I want every 500ms check if hardware action is done or not
let actionCheckSubscription = IntervalObservable.create(500).subscribe(
() => {
//So my question is, can I unsubscribe the actionCheckSubscription in here on condition change? For example,
if (this.intervalCheckingStatus(result_id))
actionCheckSubscription.unsubscribe() ;
}
) ;
})
})
}
}
You could use
Observable.from
andconcatMap
to iterate through all the items and then use afilter
in combination withtake(1)
to stop an interval as soon as the validation passes thefilter
:Here is a live-example with mock-data
So you want to make a POST request every 500 ms and then check its response. I assume your method intervalCheckingStatus evaluates the POST response and determines whether it's different?
First, I wouldn't use IntervalObservable. Have you imported the RxJS module? It's the third party library endorsed by Angular and the one they use in all their developer guide samples. If not, install it and import it. https://github.com/Reactive-Extensions/RxJS
I assume you've already imported Http, ResponseOptions etc but here it is in case others are curious:
EDIT 1: Forgot to include the dependency injection. Inject Http into your constructor. I've called it http, hence how I'm calling this.http.post
Then, I would do the following:
EDIT 2: This would be inside your loop where the post arguments are relevant to the item in your array.
If you need to do something once the response has the status (or whatever property) you're looking for, then chain a .subscribe to the end and perform the action you need in there. Again, due to take(1), as soon as the first element is pumped, the observable stream completes and you do not need to unsubscribe.
Also, here is a very helpful website: http://rxmarbles.com/#take You can see that in their example, the resulting observable is complete (vertical line) after 2 elements are taken.