RxJava:如何创建一次获取和重用的Observable? [英] RxJava: How do I make a fetch-once-and-reuse Observable?

查看:152
本文介绍了RxJava:如何创建一次获取和重用的Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在每个应用程序启动时,我都有一个Retrofit Observable,用于从服务器获取用户的用户名。我想为每个后续订阅者使用此值,但似乎每次调用subscribe()时,都会从网络中重新获取该值。由于用户名在应用程序的生命周期中不太可能发生变化,因此我不会重新创建Observable对象,只会实例化一次。

On every app launch, I have a Retrofit Observable that fetches the user's username from a server. I want to use this value for every subsequent subscriber, but it seems like every time I call subscribe(), the value is re-fetched from the network. Since the username isn't likely to change during the app's lifecycle, I'm not recreating the Observable object, only instantiating once.

我希望它如何工作:

创建一次Observable

Create the Observable once

获取用户名一次,将该值保存在Observable中

Fetch the username once, save that value in the Observable

在订阅时,使用该保存的值,或者如果未完成提取,则等待提取

On subscribe, use that saved value, or if it's not done fetching, wait for it to be fetched

我该怎么办?关于这个?

How should I go about this?

推荐答案

详细说明David的正确答案,这里有一些代码说明了使用缓存

To elaborate on David's correct answer, here's some code that illustrates the use of cache:

public class Caching {
    public static void main(String[] args) throws IOException {
        Observable<String> observable = doSomethingExpensive().cache();
        observable.subscribe(System.out::println);
        observable.subscribe(System.out::println);
    }

    private static Observable<String> doSomethingExpensive(){
        return Observable.create(subscriber -> {
            System.out.println("Doing something expensive");
            subscriber.onNext("A result");
            subscriber.onCompleted();
        });
    }
}

请注意,即使您获得两次结果,只做一次昂贵的事情。

Note that, even though you get results twice, you only do something expensive once.

这篇关于RxJava:如何创建一次获取和重用的Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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