我正在做更多的RxJava实验,主要是试图找出适用于我的业务的设计模式。我创建了一个简单的航班跟踪应用程序,可跟踪多个航班,并在航班移动时作出相应的反应。
假设我有Collection<Flight>
个Flight
个对象。每个航班都有一个Observable<Point>
,指定收到的最新坐标。如何从observable中提取最新的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
}
}
答案 0 :(得分:2)
这是实现此目的的一种方法,主要是通过创建BlockingObservable。这是不稳定的,因为如果底层的observable没有完成,它有可能挂起:
observableLocation.toBlocking().last()