我正在向服务器发送一个简单的get方法,并使用RxJava和Retrofit获得结果。我所做的是:

接口

public interface Posts {

    @GET("/typicode/demo/{path}")
    Observable<List<Beans>> getPosts(@Path("path") String path);
}


RetrofitInstance

public static Retrofit getInstance() {
        if (retrofit == null) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                    .client(client)
                    .build();
        }
        return retrofit;
    }


主要活动

Observer<List<Beans>> observer = new Observer<List<Beans>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<Beans> value) {
                Log.d("Saket", value.toString());
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };
        Posts client = RetrofitClientInstance.getInstance().create(Posts.class);
        client.getPosts("posts").observeOn(Schedulers.newThread()).subscribeOn(AndroidSchedulers.mainThread()).subscribe(observer);


我正在使用HTTPLoggingInterceptor获得正确的输出。

最佳答案

您可以像这样使用subscribeWith

也更改订阅-> Schedulers.newThread()或Schedulers.io()
现在,您正在通过UI线程进行网络调用

 client.getPosts("posts")
                    .subscribeOn(Schedulers.newThread()) // change
                    .observeOn(AndroidSchedulers.mainThread()) // change
                    .subscribeWith(new Observer<Response<Observable<List<Beans>>>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Response<Observable<List<Beans>>> response) {

                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();


                        }

                        @Override
                        public void onComplete() {


                        }
                    });

关于java - Retrofit2 + RxJava向OnNext()中的Model类返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57268956/

10-13 02:53