RxJava而不是改造回调

我是新来使用RxJava和我有问题,我怎么能改变我的新回调从RxJava的改造?RxJava而不是改造回调

我的工作代码是在这里:

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

回答:

您需要注册一个调用适配器工厂与Retrofit可以创建RxJava类型。

This is the library you need。它添加到您的build.gradle像这样:

compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' 

然后,当你建立你的改造实例,添加适配器工厂,像这样:

Retrofit.Builder() 

.baseUrl("https://example.com/")

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

.build();

以上是 RxJava而不是改造回调 的全部内容, 来源链接: utcz.com/qa/267057.html

回到顶部