首页 > 解决方案 > 在 rxjava 中订阅消费者?

问题描述

我在我的代码中替换了对 Consumer 的操作调用,但是在订阅它时一直要求我将其投射到观察者

下面是代码

public void fetchSubscriptionPlans(String url, String apiKey, String authToken,
                                   final Consumer<List<ContentDatum>> subscriptionPlans) {
    appCMSSubscriptionPlanRest.getPlansById(url,authHeaders).enqueue(new Callback<List<ContentDatum>>() {
        @Override
        public void onResponse(Call<List<ContentDatum>> call, Response<List<ContentDatum>> response) {
            try {

                Observable.just(response.body())
                        .onErrorResumeNext(throwable -> Observable.empty())
                        .subscribe(subscriptionPlans);
            } catch (Exception e) {
                Observable.just((List<ContentDatum>) null)
                        .onErrorResumeNext(throwable -> Observable.empty())
                        .subscribe(subscriptionPlans);
            }
        }

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

        }
    });
}

我得到错误.subscribe(subscriptionPlans);将其转换为.subscribe((Observer<? super List<ContentDatum>>) subscriptionPlans);

正确的方法应该是什么?

在运行代码时,我得到了异常

cannot be cast to rx.Observer

标签: androidretrofitrx-javarx-java3

解决方案


我对 Observable 的导入错误。必须使用这个

io.reactivex.rxjava3.core.Observable

推荐阅读