RXJava & Retrofit

来源:互联网 发布:厦门三套网络电视台 编辑:程序博客网 时间:2024/06/05 11:23
public class Api {    public static  final  String BASE_PATH = "http://service.meiyinkeqiu.com/service/";    public static final String BASE_URL = "https://api.github.com/";

}

public interface ApiService {    /**     * 结合Retrofit+RxJava     * thtp://service.meiyinkeqiu.com/service/ads/cptj     * @param     * @return     */    @GET("ads/cptj")    Observable<News> getNoParams();    /**     * 结合RxJava     * @param user     * @return     * https://api.github.com/users/forever     */    @GET("users/{user}")    Observable<User>  getHasParams(@Path("user")String user);}
public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        getNoParams();    }    private void getNoParams() {        Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.BASE_PATH).addConverterFactory(GsonConverterFactory.create())                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//支持RxJava                .build();        ApiService apiService = retrofit.create(ApiService.class);        //得到Observable        Observable<News> observable = apiService.getNoParams();//生产事件        //被观察者订阅观察 默认在同一个线程         observable.subscribeOn(Schedulers.io())//指定IO做耗时操作                .observeOn(AndroidSchedulers.mainThread())//指定更新UI在主线程                .subscribe(new Observer<News>() {                    @Override                    public void onCompleted() {//完成                    }                    @Override                    public void onError(Throwable e) {//失败                        Log.i("xxx", e.getMessage());                    }                    @Override                    public void onNext(News news) {//消费事件                        List<News.AdsBean> ads = news.getAds();                        for (int i = 0; i < ads.size(); i++) {                            News.AdsBean adsBean = ads.get(i);                            String gonggaoren = adsBean.getGonggaoren();                            Log.i("xxx", gonggaoren);                        }                    }                });    }}

compile 'com.android.support:appcompat-v7:26.+'compile 'com.android.support.constraint:constraint-layout:1.0.2'testCompile 'junit:junit:4.12'compile 'com.squareup.retrofit2:retrofit:2.0.1'compile 'com.squareup.okio:okio:1.5.0'compile 'com.squareup.okhttp3:okhttp:3.2.0'compile 'com.squareup.retrofit2:converter-gson:2.0.1'compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'


原创粉丝点击