获取 Observable 的最新值并立即发出 [英] Get the latest value of an Observable and emit it immeditely

查看:34
本文介绍了获取 Observable 的最新值并立即发出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取给定 Observable 的最新值并让它发出一旦被调用,立即.以下面的代码为例:

I'm trying to get the latest value of a given Observable and get it to emit immediately once it's called. Given the code below as an example:

return Observable.just(myObservable.last())
    .flatMap(myObservable1 -> {
        return myObservable1;
    })
    .map(o -> o.x) // Here I want to end up with a T object instead of Observable<T> object

这是行不通的,因为这样做 flatMap 将发出 myObservable1 ,而后者将有发射以到达 map.我不知道这样做是否可能.有没有人知道如何实现这个目标?谢谢

This does not work because by doing this the flatMap will emit myObservable1 which in turn will have to emit to reach the map. I don't know if doing such a thing is even possible. Does anyone have any clue on how to achieve this goal? Thank you

推荐答案

last() 方法在这里没有任何帮助,因为它等待 Observable 终止以提供最后发出的项目.

last() method will not be of any help here as it waits for the Observable to terminate to give you the last item emitted.

假设您无法控制发出的 observable,您可以简单地创建一个 BehaviorSubject 并将其订阅到发出您想要收听的数据的 observable,然后订阅创建的主题.由于 Subject 既是 Observable 又是 Subscriber 你会得到你想要的.

Assuming that you do not have the control over the emitting observable you could simply create a BehaviorSubject and subscribe it to the observable that emits the data that you want to listen and then subscribe to the created subject. Since Subject is both Observable and Subscriber you will get what you want.

我认为(现在没有时间检查)您可能必须手动取消订阅原始 observable,因为 BehaviorSubject 一旦他的所有订阅者取消订阅将不会自动取消订阅.

I think (do not have the time to check it now) you may have to manually unsubscribe from the original observable as the BehaviorSubject once all of his subscribers unsubscribe will not unsubscribe automatically.

像这样:

BehaviorSubject subject = new BehaviorSubject();
hotObservable.subscribe(subject);
subject.subscribe(thing -> {
    // Here just after subscribing 
    // you will receive the last emitted item, if there was any.
    // You can also always supply the first item to the behavior subject
});

http://reactivex.io/RxJava/javadoc/rx/subjects/BehaviorSubject.html

这篇关于获取 Observable 的最新值并立即发出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆