0

I need to do the following in Angular 2:

  1. Fetch data (using Observable)
  2. Validate data.
  3. IF valid THEN return data ELSE goto step1 above (fetch data)
  4. Continue until valid data found

Putting an observable in a for loop fires the observable multiple times immediately. This is a bad approach. What's a good approach?

2 Answers 2

2

Observables have a retry method which you can use by throwing an error as long as the data is not valid:

let src: Observable<any>;// the source Observable
src.map(data => {
  if (!validate(data)) {
     throw "Invalid data";
  }
  return data;
})
.retry() // you can limit the number of retries
.subscribe(data => {
   // Do something with the data
});

you can use retryWhen if you need to check the error:

let src: Observable<any>;// the source Observable
src.map(data => {
  if (!validate(data)) {
     throw "Invalid data";
  }
  return data;
})
.retryWhen(errors => errors.map(err => {
   if (err != "Invalid data") {
    throw err;
   }
 })
.subscribe(data => {
   // Do something with the data
});
Sign up to request clarification or add additional context in comments.

Comments

1

Use recursive function calls.

Fetching function:

public getData(): Observable<any> {}

Usage:

public refresh() {
   this.yourService.getData().subscribe(data => {
      // validate data !
      if (dataValid(data) {
         // do something cool here .. !
      }
      else {
         this.refresh(); // do it again ..
      }
   });
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.