Search code examples
rx-java2

RxJava - how to use methods from type referenced by Flowable?


I have two Flowables, which I manipulate by zipping and filtering like this:

Flowable<Position> position1 = obj1.getPosition(); // position in 3D enviroment
Flowable<Position> position2 = obj2.getPosition();

position1.zipWith(position2, (pos1, pos2) ->
    getDistance(pos1,pos2) //method returning distance between positions
).filter(distance->distance<=5).subscribe();

Now I want to use methods in class Position, when filtered item got emitted like this:

position1.zipWith(position2, (pos1, pos2) ->
    getDistance(pos1,pos2) //method returning distance between positions
).filter(distance->distance<=5).subscribe(pos1.getX()-pos2.getX());

How to do that?


Solution

  • The simplest way to solve that is creating wrapper class like this one

    class Line {
        Position first;
        Position second;
        Double distance;
    }
    

    and transform your Rx chain using it

    position1
        .zipWith(position2, (pos1, pos2) -> {
            double distance = getDistance(pos1,pos2);
            return Line(pos1, pos2, distance);
         })
        .filter(line -> line.distance <= 5)
        .subscribe(line.first.getX()-line.second.getX())