java - 如何从 Observable 中提取最后一个值并返回它?

标签 java reactive-programming rx-java

我正在做一些更多的 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/

相关文章:

java - 使用 values.xml 设置 Android Activity 屏幕方向

java - bean 类 [org.springframework.ldap.core.LdapTemplate] 的属性 'defaultCountLimit' 无效

objective-c - 如何保证 ReactiveCocoa 中订阅者消息的顺序?

java - 以 react 方式从流中删除已经在数据库中的对象

java - 何时使用 Mono.never()?

java - 如何通过超时简化 rxjava 流

Java 用 "broken vertical bar"分割 ISO-8859-1 字符串

java - 将 SQL 查询转换为 Android Azure 移动服务查询 - DISTINCT 语句

android - RxJava - 无法在未调用 Looper.prepare() 的线程内创建处理程序 - API 16

android - RXJava + 改造。每 n 秒重复一次请求