最近在學習RxJava 感覺很happy ,happy的同時遇到不少問題 沒辦法一點一點來 上張帥圖先
在使用RxJava + Retrofit 的時候 有時候接口請求參數不規范
比如 {}
@FormUrlEncoded
@POST("get_info")
Observable<String> getInfo(@Field("{}") String json);
但是怎么既能夠返回
new BaseSubscribe<String>()
有能夠返回
new BaseSubscribe<實體類呢?>()
查到
ScalarsConverterFactory scalarsConverterFactory = ScalarsConverterFactory.create();
.addConverterFactory(scalarsConverterFactory)來增加字符串請求
使用
GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create();
.addConverterFactory(gsonConverterFactory)增加實體類請求
但是 我這樣做了卻不行
后來查到 要這樣才行==
可能是版本問題吧。。
GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(new Gson());
ScalarsConverterFactory scalarsConverterFactory = ScalarsConverterFactory.create();
.baseUrl(ConstantApi.baseUrl)
.addConverterFactory(scalarsConverterFactory)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
別忘了:
//RxJava與Retrofit的適配器
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
參考 :http://www.th7.cn/Program/Android/201605/851109.shtml
http://www.jianshu.com/p/dbc46cc033fb
感謝作者
最后截個圖看一下目前的代碼結構 很酸爽有木有。。。
另外關於新手使用RxJava需要注意的:
subscriptions = new CompositeSubscription();
service = GithubService.createGithubService(githubToken);
view.setOnClickListener( v -> {
Subscription sub = service.user(name)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(System.out::println);
subscriptions.add(sub);
});
new CompositeSubscription();來添加 每次請求返回的Subscription對象 記得在BaseActivity中subscription.unsubscribe();
參考:http://blog.chengyunfeng.com/?p=1010感謝 原作者原文中還有很多值得研究學習的東西