如何使用Retrofit 2.0从其他线程获得响应

时间:2016-07-15 07:50:33

标签: java android json multithreading retrofit

我使用改造2来获取JSON Array并且我想创建新的ManagerListAdapter(它是RecyclerView的适配器)并传递ArrayList(我从JSON获得) )在构造函数中。

目前我在onResponse成功获得此列表。 但这是另一个主题。

将它转移到主线程的最佳方法是什么? 也许我需要使用RxJava和RxAndroid?

 private void initRecyclerView() {
        RecyclerView managersRecyclerView = (RecyclerView) view.findViewById(R.id.managersRecyclerView);
        managersRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        managersRecyclerView.setAdapter(new ManagerListAdapter(getManagers()));




//        getRemoteManagers();


    }

private void getRemoteManagers() {

    ApiObject client = ServiceGenerator.createService(ApiObject.class);
    Call<List<ManagerDTO>> call = client.getManagers();


    call.enqueue(new Callback<List<ManagerDTO>>() {
        @Override
        public void onResponse(Call<List<ManagerDTO>> call, Response<List<ManagerDTO>> response) {


            if (response.isSuccessful()) {

                List<ManagerDTO> managers = response.body(); //I want to  add this List in RecyclerAdapter
                sortManagers(managers);

            }

        }

        @Override
        public void onFailure(Call<List<ManagerDTO>> call, Throwable t) {

        }
    });


}


private List<ManagerDTO> getManagers() {

//It's for test. 

    List<ManagerDTO> managers = new ArrayList<>();

    managers.add(new ManagerDTO("Alex Pavlov", 100));
    managers.add(new ManagerDTO("Ivan Pavlov", 95));
    managers.add(new ManagerDTO("Petr Pavlov", 99));
    managers.add(new ManagerDTO("Stepan Pavlov", 100));
    managers.add(new ManagerDTO("Azik Pavlov", 100));
    managers.add(new ManagerDTO("Azik Myand", 100));
    managers.add(new ManagerDTO("Azik Specca", 50));
    managers.add(new ManagerDTO("Azik Kane", 0));
    managers.add(new ManagerDTO("Azik McDonald", 99));
    managers.add(new ManagerDTO("Azik Jagr", 1));

    sortManagers(managers);

    return managers;


}

1 个答案:

答案 0 :(得分:0)

我们可以将RxJavaRxAndroidRetrifit2一起使用。

<强> ServiceGenerator:

private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                    .baseUrl(Const.URL.UrlService)
                    .addConverterFactory(JacksonConverterFactory.create());


   public static <S> S createService(Class<S> serviceClass) {

        Retrofit retrofit = builder.build();
        return retrofit.create(serviceClass);
    }
}

请求:

ApiObject service = ServiceGenerator.createService(ApiObject.class);
        Observable<List<ManagerDTO>> observManagers = service.getManagers();
        observManagers
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ManagerDTO>>() {
                    @Override
                    public void onCompleted() {
                        //do nothing
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("OnError", e.getMessage());
                        Toast.makeText(context, R.string.toast_connection_false, Toast.LENGTH_SHORT).show();
                        initRecyclerView(Cache.getManagers());
                        managersSwipe.setRefreshing(false);
                    }

                    @Override
                    public void onNext(List<ManagerDTO> managers) {
                        Log.e("OnNext", "Connect is OK");
                        sortManagers(managers);
                        Cache.setManagerDTO(managers);
                        initRecyclerView(managers);
                        managersSwipe.setRefreshing(false);

                        //Copy to db
                        RealmHelper helper = new RealmHelper(context);
                        helper.copyToRealmOrUpdate(managers);
                        Log.e("RealmCopy", "it's ok");
                    }
                });
    }