RXJava订阅不可转换类型;无法将“ void”转换为“ org.reactivestreams.Subscription”?

时间:2018-11-24 11:31:10

标签: java android rx-java2 rx-android

我正在尝试使用Retrofit和RxJava在正在处理的应用程序的自定义视图中进行API调用,但是尝试从Retrofit API调用订阅Observable时遇到类型不兼容的错误。 / p>

  

ApiService

public interface ApiService {
@GET("airline-tickets.php")
Observable<List<Ticket>> getStarredRepositories();
}
  

ApiClient

public class ApiClient {
private static final String GITHUB_BASE_URL = "https://api.androidhive.info/json/";
private ApiService apiService;
private static ApiClient instance;

public ApiClient() {
    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(GITHUB_BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    apiService = retrofit.create(ApiService.class);
}

public static ApiClient getInstance() {
    if (instance == null) {
        instance = new ApiClient();
    }
    return instance;
}

public Observable<List<Ticket>> getStarredRepos() {
    return apiService.getStarredRepositories();
}
}
  

MainActivity

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Subscription subscription= (Subscription) ApiClient.getInstance()
            .getStarredRepos()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<Ticket>>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(List<Ticket> tickets) {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
}
}
  

这部分代码显示不可转换的类型;无法将'void'强制转换为'org.reactivestreams.Subscription

Subscription subscription= (Subscription) ApiClient.getInstance()
            .getStarredRepos()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<Ticket>>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(List<Ticket> tickets) {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

1 个答案:

答案 0 :(得分:1)

使用subscribeWith返回您传递给该方法的Observer。您可能正在使用旧的RxJava 1代码。 RxJava 2 API有所更改。 Observable现在接受Observer,您应该将Subscription更改为Observer