Rxjava和retorfit的混合使用

1.导入依赖

compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
compile 'com.facebook.fresco:fresco:0.11.0'
compile 'com.facebook.fresco:animated-gif:0.12.0'

2、添加权限
<uses-permission android:name="android.permission.INTERNET">uses-permission>

3.布局文件

activity_main中

<android.support.v7.widget.RecyclerView
    android:id="@+id/id_recyclerview"
    android:divider="#ffff0000"
    android:dividerHeight="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

item_home中

<TextView
    android:id="@+id/id_num"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:text="1" />

<com.facebook.drawee.view.SimpleDraweeView
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:id="@+id/main_simple_drawee_view"
    fresco:placeholderImage="@mipmap/ic_launcher"/>

bean类

public class Suppercalss {

    /**
     * code : 200
     * msg : success
     * newslist : [{"ctime":"2017-10-26 07:53","title":"如何看待历史剧? 媒体:把握好不虚与不拘","description":"搜狐社会","picUrl":"","url":"http://news.sohu.com/20171026/n519914029.shtml"},{"ctime":"2017-10-14 08:40","title":"西安一楼盘迟迟办不下证 460业主起诉开发商","description":"搜狐社会","picUrl":"","url":"http://news.sohu.com/20171014/n517767283.shtml"},{"ctime":"2017-10-03 20:41","title":"家国网事|因为这10元钱,70岁老人哭了两次,冒雨也要还!","description":"搜狐社会","picUrl":"http://photocdn.sohu.com/20171003/Img515929518_ss.jpeg","url":"http://news.sohu.com/20171003/n515929517.shtml"},{"ctime":"2017-09-30 13:28","title":"\u201c拒绝妻子手术\u201d现场医生:病人丈夫被冤枉了","description":"搜狐社会","picUrl":"http://photocdn.sohu.com/20170930/Img515443705_ss.jpeg","url":"http://news.sohu.com/20170930/n515443704.shtml"},{"ctime":"2017-09-30 08:54","title":"黑作坊用荷叶粉制减肥药 一盒220元每粒成本3毛","description":"搜狐社会","picUrl":"","url":"http://news.sohu.com/20170930/n515392928.shtml"},{"ctime":"2017-09-12 07:45","title":"80后团队操盘新媒体 六百岁故宫就这样炼成\u201c网红\u201d","description":"搜狐社会","picUrl":"http://photocdn.sohu.com/20170911/Img510908418_ss.jpeg","url":"http://news.sohu.com/20170911/n510908417.shtml"},{"ctime":"2017-09-04 06:40","title":"【塞罕坝造林人系列】刘军夫妇:做\u201c林场眼睛\u201d11年 无畏坚守护好绿","description":"搜狐社会","picUrl":"http://photocdn.sohu.com/20170903/Img509482875_ss.jpeg","url":"http://news.sohu.com/20170903/n509482874.shtml"},{"ctime":"2017-08-09 00:31","title":"辟谣:九寨沟县地震部分谣言网上流传 请大家不信谣不传谣","description":"搜狐社会","picUrl":"http://photocdn.sohu.com/20170809/Img505992955_ss.jpeg","url":"http://news.sohu.com/20170809/n505992954.shtml"},{"ctime":"2017-06-07 10:12","title":"舍不得媳妇套不住流氓!警察带女友约会\u201c钓色魔\u201d","description":"搜狐社会","picUrl":"","url":"http://news.sohu.com/20170607/n495984947.shtml"},{"ctime":"2017-06-06 06:19","title":"专题 | 三分钟带你看遍苹果WWDC 2017亮点","description":"网易VR","picUrl":"http://img4.cache.netease.com/photo/0009/2017-06-06/s_CM7TROL26PGI0009.jpg","url":"http://tech.163.com/special/S1496632396292/"}]
     */

    private int code;
    private String msg;
    private List newslist;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List getNewslist() {
        return newslist;
    }

    public void setNewslist(List newslist) {
        this.newslist = newslist;
    }

    public static class NewslistBean {
        /**
         * ctime : 2017-10-26 07:53
         * title : 如何看待历史剧? 媒体:把握好不虚与不拘
         * description : 搜狐社会
         * picUrl :
         * url : http://news.sohu.com/20171026/n519914029.shtml
         */

        private String ctime;
        private String title;
        private String description;
        private String picUrl;
        private String url;

        public String getCtime() {
            return ctime;
        }

        public void setCtime(String ctime) {
            this.ctime = ctime;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}

3创建MyApplication继承Application

public class MyApplication extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);
    }
}
4创建适配器 HomeAdapter

public class HomeAdapter extends RecyclerView.Adapter {

    Context context;
    List list;

    public HomeAdapter(MainActivity context, List list) {
        this.list = list;
        this.context = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
               context).inflate(R.layout.item_home, parent,
                false));
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
       MyViewHolder myViewHolder=(MyViewHolder) holder;
        myViewHolder.tv.setText(list.get(position).getTitle());

        Uri uri =  Uri.parse(list.get(position).getPicUrl());
        myViewHolder.sdv.setImageURI(uri);


    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder
    {

        TextView tv;
        SimpleDraweeView sdv;

        //        SimpleDraweeView sdv;
        public MyViewHolder(View view)
        {
            super(view);
            tv = (TextView) view.findViewById(R.id.id_num);
            sdv = view.findViewById(R.id.main_simple_drawee_view);
        }
    }
}

5mainactivity中使用

public class MainActivity extends AppCompatActivity {
//     TextView tv;
    private RecyclerView mRecyclerView;
    private List newslist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        tv = (TextView) findViewById(R.id.tv);

        mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//        mRecyclerView.setAdapter(mAdapter = new HomeAdapter());
//        getNoParams();
        getEr();
    }

    public void getNoParams() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.BASE_PATH).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
        //通过动态代理得到网络接口对象
        //http://service.meiyinkeqiu.com/service/ads/cptj
        ApiService apiService = retrofit.create(ApiService.class);
        //得到Observable
        Observable observable = apiService.getNoParams();
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onCompleted() {
                        Toast.makeText(MainActivity.this,"onCompleted",Toast.LENGTH_LONG);
                        Log.d("main", "onCompleted: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(MainActivity.this,"onCompleted",Toast.LENGTH_LONG);
                        Log.d("main", "onError: ");
                    }

                    @Override
                    public void onNext(News news) {
                        List ads = news.getAds();
                        for (int i=0;i//                            tv.setText(ads.get(i).getGonggaoren());
                        }
                    }
                });

    }
    public void getEr(){
       Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.GUO_NEI).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
        ApiService service = retrofit.create(ApiService.class);
        Observable er = service.getEr();
        er.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Suppercalss suppercalss) {
                        newslist = suppercalss.getNewslist();
//                        for (int i = 0; i< newslist.size(); i++){
//                            tv.setText(newslist.get(i).getTitle());
//                        }
                        HomeAdapter homeAdapter = new HomeAdapter(MainActivity.this, newslist);
                        mRecyclerView.setAdapter(homeAdapter);

                    }
                });
    }
}

7.创建Api类

public class Api {
    public static final String BASE_PATH="http://service.meiyinkeqiu.com";
    public static final String GUO_NEI="http://api.tianapi.com";
}
8.创建 ApiService接口、

public interface ApiService {
    @GET("/service/ads/cptj")
    Observable getNoParams();

    @GET("/social/?key=ac87b4a4e634eb4a4e96fd371490a667&num=10")
     Observable getEr();


}

你可能感兴趣的:(Rxjava和retorfit的混合使用)