使用Retrofit和Rxjava时出错

时间:2016-07-04 10:15:22

标签: android rx-java retrofit2

我正在尝试实现RxJava和Retrofit2。但我收到此错误java.lang.IllegalArgumentException:无法为rx.Observable创建调用适配器

这是我的代码: - MainActivity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button bFetch = (Button) findViewById(R.id.button_fetch);
    assert bFetch != null;
    bFetch.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            GithubService service;

            final Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(GithubService.SERVICE_ENDPOINT)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            service = retrofit.create(GithubService.class);

            Observable<Github> observable = service.getUser("writingminds");
            observable.subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Github>() {
                        @Override
                        public final void onCompleted() {
                            // do nothing
                        }

                        @Override
                        public final void onError(Throwable e) {
                            Log.e("GithubDemo", e.getMessage());
                        }

                        @Override
                        public final void onNext(Github response) {
                            Log.e("---%s", response.getBlog());
                            Log.e("--%s", response.getLogin());
                        }
                    });
        }
    });
}

}

这是我的Interface GithubService

public interface GithubService {
String SERVICE_ENDPOINT = "https://api.github.com";

@GET("/users/{login}")
Observable<Github> getUser(@Path("login") String login);
}

这是我的模特:

public class Github {
private String login;
private String blog;
private int public_repos;

public String getLogin() {
    return login;
}

public String getBlog() {
    return blog;
}

public int getPublicRepos() {
    return public_repos;
  }
}

提前谢谢

1 个答案:

答案 0 :(得分:2)

你需要告诉Retrofit,你想要使用RxJava。你可以用

来做
addCallAdapterFactory(RxJavaCallAdapterFactory.create())

E.g

final Retrofit retrofit = new Retrofit.Builder()
   .baseUrl(GithubService.SERVICE_ENDPOINT)
   .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
   .addConverterFactory(GsonConverterFactory.create())
   .build();

你必须添加

compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

到您的build.gradle依赖关系列表,如果您还没有