2017-12-27 153 views
0

我是新來使用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 

回答

0

您需要註冊一個調用適配器工廠與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();