Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an observable by an observable

Tags:

rxjs

reactivex

Let's consider the following simplified situation:

  • We have an Observable apples of type Observable < Apple >
  • Every Apple object has a method isRotten() which returns an observable of type Observable < Boolean > which is guaranteed to emit at least one boolean value.

I want to filter the apples observable such that the rotten apples don't pass the filter. More precisely, an apple A passes the filter if and only if the first item emitted by A.isRotten() is false. What is the best way to implement this filter?

After some thinking I could come up with this:

apples
    .concatMap(apple => 
        apple.isRotten()
            .first()
            .filter(bool => bool)
            .map(bool => apple))

Which is written in javascript. ( ... => ... is a function). This works, but I think it is rather lengthy and difficult to understand. Is there a better way to do this kind of thing?

like image 639
Ward Beullens Avatar asked Jul 23 '16 20:07

Ward Beullens


People also ask

How do you filter values from Observable?

The RxJS filter() operator is like the well-known Array Array . prototype. filter() method. This operator takes values from the source Observable, passes them through a predicate function and only emits those values that get TRUE.

Which operator will filter the values from source Observable based on the predicate function given?

This operator will filter the values from source Observable based on the predicate function given.

Can you subscribe to an Observable?

Subscribinglink An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.

What is filter operator in Angular?

The Filter Operator in Angular filters the items emitted by the source Observable by using a condition (predicate). It emits only those values, which satisfies the condition and ignores the rest.


1 Answers

What you've got is fine and, tbh, I can't think of a more concise way of doing it. I'd probably use flatMap rather than concatMap if out-of-order apples aren't an issue.

If readibility is an issue for you, just move the implementation into it's one function (eg. filterObservable that accepts a function that takes a value and returns an IObservable<bool>)

like image 107
Richard Szalay Avatar answered Oct 21 '22 04:10

Richard Szalay