1
我正在做更多的RxJava实验,主要是试图找出适合我业务的设计模式。我创建了一个简单的跟踪多个航班的航班跟踪应用程序,并在航班移动时做出相应反应。如何从Observable中提取最后一个值并将其返回?
假设我有一个Collection<Flight>
与Flight
对象。每个航班都有一个Observable<Point>
指定收到其位置的最新坐标。如何从observable中提取最新的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
}
}
同意,太过迫切。您应该将信息传递给订阅中需要的信息。 –
我很担心这一点。如果你将某些可观察的东西变成不可观察的东西,我想它会击败目的。 – tmn
如果你是一个纯粹主义者,是的。你可能更务实。 ;) –