Single Observable with Multiple Subscribers

后端 未结 2 1244
梦如初夏
梦如初夏 2020-11-29 22:09

I have an Observable<> getFoo() that is created from a Retrofit Service and after calling the .getFoo() method, I need to

2条回答
  •  再見小時候
    2020-11-29 22:26

    You seem to be (implicitly) casting your ConnectedObservable returned by .share() back into a normal Observable. You might want to read up on the difference between hot and cold observables.

    Try

    ConnectedObservable> testObservable = retrofit
            .create(GitHub.class)
            .contributors("square", "retrofit")
            .share();
    
    Subscription subscription1 = testObservable
       .subscribe(new Subscriber>() {
        @Override
        public void onCompleted() {
    
        }
    
        @Override
        public void onError(Throwable throwable) {
    
        }
    
        @Override
        public void onNext(List contributors) {
            System.out.println(contributors);
        }
    });
    
    Subscription subscription2 = testObservable
            .subscribe(new Subscriber>() {
                @Override
                public void onCompleted() {
    
                }
    
                @Override
                public void onError(Throwable throwable) {
    
                }
    
                @Override
                public void onNext(List contributors) {
                    System.out.println(contributors + " -> 2");
                }
            });
    
    testObservable.connect();
    subscription1.unsubscribe();
    subscription2.unsubscribe();
    

    Edit: You don't need to call connect() every time you want a new subscription you only need it to start up the observable. I suppose you could use replay() to make sure all subsequent subscribers get all items produced

    ConnectedObservable> testObservable = retrofit
            .create(GitHub.class)
            .contributors("square", "retrofit")
            .share()
            .replay()
    

提交回复
热议问题