Как заменить мой ответ Retrofit на Rx Java Наблюдать - PullRequest
0 голосов
/ 24 февраля 2020

В моей архитектуре MVP у меня есть некоторый интерактор

interface GetNoticeIntractor {

        interface OnFinishedListener {
            void onFinished(ArrayList<Notice> noticeArrayList, Main main, Wind wind);
            void onFailure(Throwable t);
        }
        void getNoticeArrayList(OnFinishedListener onFinishedListener);

    }

Здесь его Impl

public class GetNoticeIntractorImpl implements MainContract.GetNoticeIntractor {
    public LatLng getloc(){
        return currentLocation;
    }
    @Override
    public void getNoticeArrayList(final OnFinishedListener onFinishedListener) {


        /** Create handle for the RetrofitInstance interface*/
        GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);

        /** Call the method with parameter in the interface to get the notice data*/
        if(currentLocation!=null) {
            Call<NoticeList> call = service.getNoticeData(currentLocation.latitude, currentLocation.longitude);

            /**Log the URL called*/
            Log.wtf("URL Called", call.request().url() + "");

            call.enqueue(new Callback<NoticeList>() {
                @Override
                public void onResponse(Call<NoticeList> call, Response<NoticeList> response) {
                    onFinishedListener.onFinished(response.body().getNoticeArrayList(), response.body().getMain(), response.body().getWind());

                }

                @Override
                public void onFailure(Call<NoticeList> call, Throwable t) {
                    onFinishedListener.onFailure(t);
                }
            });
        }
    }

}

, который использует DataService

public interface GetNoticeDataService {


    @GET("weather?appid=0194877ecdcac230396a119c01d46100")
    Call<NoticeList> getNoticeData(@Query("lat") double lat , @Query("lon") double lon );

}

Вот база Rerofit с CallAdapterFactory of Rx Java

public class RetrofitInstance {
    private static Retrofit retrofit;
    private static final String BASE_URL = "http://api.openweathermap.org/data/2.5/";

    /**
     * Create an instance of Retrofit object
     * */
    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new retrofit2.Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Вопрос в том, как наблюдать мой GetNoticeIntractorImpl согласно rx java subscripton

Должен ли я изменить свой DataService на

@GET("weather?appid=0194877ecdcac230396a119c01d46100")
    Observable<NoticeList> getNoticeData(@Query("lat") double lat , @Query("lon") double lon );

Или только используйте Observable в моем IntractorImpl

Observable.create(e -> {
            Call<NoticeList> call = service.getNoticeData(currentLocation.latitude, currentLocation.longitude);

            /**Log the URL called*/
            Log.wtf("URL Called", call.request().url() + "");

            call.enqueue(new Callback<NoticeList>() {
                @Override
                public void onResponse(Call<NoticeList> call, Response<NoticeList> response) {
                    onFinishedListener.onFinished(response.body().getNoticeArrayList(), response.body().getMain(), response.body().getWind());

                }

                @Override
                public void onFailure(Call<NoticeList> call, Throwable t) {
                    onFinishedListener.onFailure(t);
                }
            });

Мне нужны советы, какой способ реализовать это, я буду рад любой помощи

1 Ответ

0 голосов
/ 25 февраля 2020

Я бы посоветовал вам использовать официальный адаптер дооснащения для rxJava2

compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0 

А затем при создании объекта дооснащения добавьте адаптер rx java, как показано ниже

retrofit2.Retrofit.Builder
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())

И, наконец, ваш интерфейс API должен выглядеть так:

@GET("weather?appid=0194877ecdcac230396a119c01d46100")
Observable<NoticeList> getNoticeData(@Query("lat") double lat , @Query("lon") double lon );

И способ его вызова может быть таким:

endpoints.getNoticeData(lat,long).subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread()).
  .subscribe(new Consumer<List<NoticeList>>() {
     @Override
     public void accept(@io.reactivex.annotations.NonNull final List<NoticeList> items)
      {
        //Use your response here
      }
    })
  ); 
...