How to ensure that all observers see the same result from multiple parallel subscription

℡╲_俬逩灬. 提交于 2020-01-11 13:15:10

问题


I have two observables.
First - get session from internet or from cache;

Observable<SessionKey> getSession = getSessionFromInternetOrCache();

Second - call to server api, using session

Observable<MyResult> apiCall = getSession.flatMap(session -> {
    return myApi.getResult(session);
})

Problem, that I have several independent components (gui). They are starting in parallel. apiCall also started in parallel. And i gets several session keys.

What behavior I want: getSessions should calling once, other observables waiting first getSessions call. After first getSessions calling, all getSessions will be return cached session;

What idea to implement that behaviour?

UPD Behavior should be: Retrieving session from internet should block other getSessions calls, until session not will be cached.


回答1:


You can call cache() on the returned Observable in getSessionFromInternetOrCache and it will make sure the session will be retrieved only once and replayed to anyone trying to observe it later. I assume the actual session retrieval only happens when one subscribes to the Observable.

Edit: this example shows what I meant:

public class SingleSessions {
    static Observable<String> getSession;
    public static void main(String[] args) throws Exception {
        getSession =
                Observable.just("abc")
                .doOnSubscribe(() -> System.out.println("This should happen once")) 
                .delay(500 + new Random().nextInt(2) * 700, TimeUnit.MILLISECONDS)
                .timeout(1000, TimeUnit.MILLISECONDS, Observable.just("cde"))
                .cache();

        System.out.println("Asking for the session key");

        getSession.subscribe(System.out::println);
        getSession.subscribe(System.out::println);
        getSession.subscribe(System.out::println);
        getSession.subscribe(System.out::println);

        System.out.println("Sleeping...");
        Thread.sleep(2000);
        System.out.println("...done");

        getSession.subscribe(System.out::println);
        getSession.subscribe(System.out::println);
    }
}


来源:https://stackoverflow.com/questions/30756552/how-to-ensure-that-all-observers-see-the-same-result-from-multiple-parallel-subs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!