1

I have a function that selects an offer, but I need to check whether this offer is in the Observable array of offers$ first.

selectOffer(offer) {
    this.offers$.subscribe(items => {
      items.forEach(item => {
        if (item === offer) {
          // if offer is in offers$, DO...
        }
      });
    });
  }

How could I transform this to work with Rxjs operators (pipe, map, filter etc..)

2
  • 1
    What's wrong with what you have now? Or you want to have an Observable that emits true/false based on whether the item is in the array? Commented Dec 17, 2019 at 9:57
  • We'll need more code. What do you expect the selectOffer to return? What kind of observable is this.offer$. Commented Dec 17, 2019 at 10:09

3 Answers 3

2

Try find operator

Emit the first item that passes predicate then complete.

selectOffer(offer) {
    this.offers$.pipe(find((item: any) => item === offer)).subscribe(items => {
        console.log("Offer is in the list")
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use .map on observables

Try like this:

selectOffer(offer) {
  this.offers$.map(item => item.filter(x => x === offer));
}

Comments

0

After trying several options, this one seemed the most effective for my case:

this.offers$
      .pipe(
        map(items =>
          items ? items.filter((item: any) => item === offer) : null)
      )
      .subscribe(item => { /* DO */ });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.