我正在做一些更多的 RxJava 实验,主要是试图找出适合我的业务的设计模式。我创建了一个简单的航类跟踪应用程序,可以跟踪多个航类,并在航类移动时做出相应 react 。
假设我有一个Collection<Flight>
与 Flight
对象。每个航类都有一个Observable<Point>
指定接收到的最新位置坐标。如何提取最新的Flight
对象本身来自可观察的对象,而不必将其保存到整个单独的变量中?有没有get()
方法或Observable
上类似的东西?还是我想得太势利了?
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()
关于java - 如何从 Observable 中提取最后一个值并返回它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30084322/