我如何从 Observable 中提取最后一个值并 return 它?

How do I extract the last value from an Observable and return it?

我正在做更多的 RxJava 实验,主要是想找出适合我的业务的设计模式。我创建了一个简单的航班跟踪应用程序来跟踪多个航班,并在航班移动时做出相应的反应。

假设我有一个 Collection<Flight>Flight 个对象。每个航班都有一个 Observable<Point> 指定其位置的最新接收坐标。如何从可观察对象中提取最新的 Flight 对象本身,而不必将其保存到一个完整的单独变量中? Observable 上没有get() 方法或类似的东西吗?还是我想得太急迫了?

public final class Flight {

    private final int flightNumber;
    private final String startLocation;
    private final String finishLocation;
    private final Observable<Point> observableLocation;
    private volatile Point currentLocation = new Point(0,0); //prefer not to have this

    public Flight(int flightNumber, String startLocation, String finishLocation) {

        this.flightNumber = flightNumber;
        this.startLocation = startLocation;
        this.finishLocation = finishLocation;
        this.observableLocation = FlightLocationManager.get().flightLocationFeed()
                .filter(f -> f.getFlightNumber() == this.flightNumber)
                .sample(1, TimeUnit.SECONDS)
                .map(f -> f.getPoint());

        this.observableLocation.subscribe(l -> currentLocation = l);
    }
    public int getFlightNumber() { 
        return flightNumber;
    }
    public String getStartLocation() { 
        return startLocation;
    }
    public String getFinishLocation() { 
        return finishLocation;
    }
    public Observable<Point> getObservableLocation() { 
        return observableLocation.last();
    }
    public Point getCurrentLocation() { 
        return currentLocation; //returns the latest observable location
        //would like to operate directly on observable instead of a cached value
    }
}

这是一种方法,主要是创建 BlockingObservable。这是片状的,因为如果底层可观察对象没有完成,它有可能挂起:

observableLocation.toBlocking().last()