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
如果你是一個純粹主義者,是的。你可能更務實。 ;) –