Right way of using RxJava + Retrofit 2

前端 未结 1 1709
醉话见心
醉话见心 2021-02-10 22:51

I have such JSON:

{  
\"success\":true,
\"data\":[  
   {  
      \"id\":\"29\",
     \"name\":\"\\u0420\\u0435\\u0441\\u0442\\u043e\\u0440\\u0430\\u0446\\u0456\         


        
相关标签:
1条回答
  • 2021-02-10 23:40

    You are using it correctly, RxJava has very much power which you can leverage in order to improve Performance.

    Where to use? 1. On user events, like Button click, Key events 2. Respond to latency bound IO. Disk/network read/write 3. Events triggered by Hardware/sensors

    Should not start Thread manually from Observable create.

    Retrofit Network call with RxJava: Use Single : As our API will not give data in a pieces or multiple times. Instead it will emit everything in just one call. So, in case of Observable onCompleted() will follow as soon as onNext() happens. So, it would be better to use Single for API calling.

    Use Completable : Whenever we need to just update data to Server through API, and We do not bother about what should be the result. We just meant if service is successful or not. In this cases we are not expecting to emit anything. So use of Completable is encouraged in the cases.

    For progress view hide/show: Bind this two events with doOnSubscribe() and doFinally(). This are two operators, so we can logically bind them with RxCall.

    RxJava Error Handling:

    onErrorResumeNext( ) — instructs an Observable to emit a sequence of items (which is another observable)if it encounters an error

    onErrorReturn( ) — instructs an Observable to emit a particular item when it encounters an error

    onExceptionResumeNext( ) — instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable)

    retry( ) — if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error. Here we can also pass argument for How many times retry should happen. Like. retry(4). It will retry four times and after that if again error occures then will throw an error.

    retryWhen( ) — if a source Observable emits an error, pass that error to another Observable to determine whether to resubscribe to the source

    RxAndroid for View Binding:

    Think Reactive: We can use RxJava for all view events including click event, scroll event, drag event. In short, we can replace every Listeners with RxJava observables.

    Available Libraries to use at View level: RxBinding, RxSupport-v4, RxAppCompat-v7, RxRecyclerView, RxDesign, RxLeanBack.

    RxBinding with MVP: We will return Observable from View. This observable will fetch to Presenter and will do Subscription at Presenter.

    RxAdapter: we can use this for data change event in Adapter. Typically available for Android Listview. RxRecyclerView: For recyclerview adapter data change events we can use this.

    0 讨论(0)
提交回复
热议问题