我是使用RxJava的新手,我对如何在RxJava上从Retrofit更改新的Callback有疑问?
我的工作代码在这里:
Service service = new Retrofit.Builder()
.baseUrl("lalala")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(Service.class);
之后我写了
Call<Board> call = service.getBoard("lalala");
call.enqueue(new Callback<Board>() {
@Override
public void onResponse(Call<Board> call, Response<Board> response) {
if (response.isSuccessful()) {
recyclerView.setAdapter(new BoardAdapter(MainActivity.this, response.body().getThreads()));
}
}
@Override
public void onFailure(Call<Board> call, Throwable t) {
Toast.makeText(MainActivity.this, "error :(", Toast.LENGTH_SHORT).show();
}
});*/
但是当我想在RxJava上使用它时,我不明白该怎么做。我试过了。
service.getRxBoard(boardq)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Board>() {
@Override
public void accept(Board board) throws Exception {
recyclerView.setAdapter(new BoardAdapter(MainActivity.this, board.getThreads()));
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Toast.makeText(MainActivity.this, "error :(", Toast.LENGTH_SHORT).show();
}
});
它不起作用。我有一个例外:
java.lang.RuntimeException: Unable to start activity ComponentInfo
Unable to create call adapter for io.reactivex.Observable
答案 0 :(得分:0)
您需要使用可以创建RxJava类型的Retrofit注册一个调用适配器工厂。
This is the library you need。将它添加到build.gradle中,如下所示:
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
然后在构建Retrofit实例时,添加适配器工厂,如下所示:
Retrofit.Builder()
.baseUrl("https://example.com/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();