我正在尝试制作一个非常基本的Retrofit / RxJava设置。所以我正在尝试使用此API:http://jsonplaceholder.typicode.com/posts
我的基本设置如下;
我的改装服务:
public interface SimpleTestService {
String endpoint = "jsonplaceholder.typicode.com";
@GET("/posts")
Observable<Post> getPosts();
}
创建服务:
public class TestAdapter {
public static SimpleTestService createService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://wwww.jsonplaceholder.typicode.com")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
SimpleTestService service = retrofit.create(SimpleTestService.class);
return service;
}
}
拨打电话:
SimpleTestService testService = TestAdapter.createService();
testService.getPosts()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Post>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Post post) {
String text = testText.getText().toString();
text += post.getBody();
testText.setText(text);
}
});
当我尝试这样做时,我得到了例外:
java.lang.IllegalArgumentException: Unable to create call adapter for rx.Observable<Post>
这对我来说很奇怪,因为我明确添加了RX调用适配器。我还在build.gradle
中包含了所有这些内容任何提示?
谢谢!
答案 0 :(得分:1)
将SimpleTask服务更改为此
public interface SimpleTestService {
String endpoint = "http://jsonplaceholder.typicode.com";
@GET("/posts")
Observable<List<Post>> getPosts();
}
通过更改基本网址
创建服务 public class TestAdapter {
public static SimpleTestService createService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SimpleTestService .endpoint)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
SimpleTestService service = retrofit.create(SimpleTestService.class);
return service;
}
}
您的电话就像是
SimpleTestService testService = TestAdapter.createService();
testService .getPosts().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(new Func1<List<Post>, Observable<Post>>() {
@Override
public Observable<Post> call(List<Post> posts) {
return Observable.from(posts);
}
})
.subscribe(new Observer<Post>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Post post) {
String text = testText.getText().toString();
text += post.getBody();
testText.setText(text);
}
});