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

前端 未结 1 1438
灰色年华
灰色年华 2021-01-28 10:00

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

Observable getSession = getSessionFromInternetOrCache();
<         


        
相关标签:
1条回答
  • 2021-01-28 10:16

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题