Manage identical requests with RxJava

前端 未结 3 823
清歌不尽
清歌不尽 2021-01-16 21:00

Assume that I have a fetcher that fetches an image from a given link on a separate thread. The image will then be cached in memory. Once the image already gets cached, the f

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-16 21:49

    Have a look at ConnectableObservable and the .replay() method.

    I'm currently using this is my fragments to handle orientation changes:

    Fragment's onCreate:

    ConnectableObservable connectableObservable = 
        retrofitService.fetchMyThing()
            .map(...)
            .replay();
    
    connectableObservable.connect(); // this starts the actual network call
    

    Fragment's onCreateView:

    Subscription subscription = connectableObservable
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(mything -> dosomething());
    

    What happens is that I make 1 network request only, and any subscriber will (eventually/immediately) get that response.

提交回复
热议问题