美文网首页Android知识
Rxjava2+retrofit2基础网络请求

Rxjava2+retrofit2基础网络请求

作者: 帝乙岩 | 来源:发表于2017-06-14 10:09 被阅读0次

    布局控件使用recyclerview+cardview
    本篇不涉及封装,只是简单的实现
    先看下目录结构

    Rxjava2目录结构.jpg
    基础布局不再复述只贴主要代码,基础布局链接
    Rxjava2实现网络请求需要的包.jpg
    需要添加的网络权限
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    先上基本代码,写了一个单例
    RetrofitManager.class

    import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
    import retrofit2.Retrofit;
    import retrofit2.converter.gson.GsonConverterFactory;
    
    public class RetrofitManager {
        static final String BASE_URL = "http://news-at.zhihu.com/api/4/news/";
        private Retrofit retrofit;
        private static RetrofitManager ourInstance = new RetrofitManager();
    
        public static RetrofitManager getInstance() {
            return ourInstance;
        }
    
        private RetrofitManager() {
        }
        /**
         * 获取retrofit单例
         * @return Retrofit single
         */
        public Retrofit getRetrofit() {
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }
    

    实体类entity.class,这里只展示主要代码

    public class entity {
     private List<StoriesBean> stories;
        public List<StoriesBean> getStories() {
            return stories;
        }
        public void setStories(List<StoriesBean> stories) {
            this.stories = stories;
        }
     public static class StoriesBean {
            private String title;
            private List<String> images;
            public String getTitle() {
                return title;
            }
            public void setTitle(String title) {
                this.title = title;
            }
            public List<String> getImages() {
                return images;
            }
            public void setImages(List<String> images) {
                this.images = images;
            }
        }
     }
    

    GetNews接口

    import com.haoyan.myrxjava.entity.Results;
    import io.reactivex.Observable;
    import okhttp3.ResponseBody;
    import retrofit2.http.GET;
    import retrofit2.http.Url;
    
    public interface GetNews {
        @GET("latest")
        Observable<Results> getNews();
    
        @GET
        Observable<ResponseBody> getPicFromNet(@Url String url);
    }
    

    主类:MainActivity.class
    主要看点是map将url转为bitmap

    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.DefaultItemAnimator;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.Toast;
    
    import com.haoyan.myrxjava.adapter.SimpleAdapters;
    import com.haoyan.myrxjava.entity.entity;
    import com.haoyan.myrxjava.http.GetNews;
    import com.haoyan.myrxjava.http.RetrofitManager;
    import com.haoyan.myrxjava.utils.MyViewHolder;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import io.reactivex.Observer;
    import io.reactivex.android.schedulers.AndroidSchedulers;
    import io.reactivex.annotations.NonNull;
    import io.reactivex.disposables.Disposable;
    import io.reactivex.functions.Consumer;
    import io.reactivex.functions.Function;
    import io.reactivex.schedulers.Schedulers;
    import okhttp3.ResponseBody;
    
    public class MainActivity extends AppCompatActivity {
        private RecyclerView mRecyclerView;
        private SimpleAdapters mAdapter;
        private List<entity.StoriesBean> storiesList;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            storiesList = new ArrayList<>();
            initViews();
            getDataByRetrofit();
        }
    
        private void initViews() {
            mRecyclerView = (RecyclerView) findViewById(R.id.main_recycler);
            mAdapter = new SimpleAdapters(this, storiesList, R.layout.item_rock) {
    
                @Override
                public void convert(final MyViewHolder holder, final entity.StoriesBean storiesList) {
                    String url = storiesList.getImages().get(0);
                    GetNews getBitmap = RetrofitManager.getInstance().getRetrofit().create(GetNews.class);
                    getBitmap.getPicFromNet(url)
                            .map(new Function<ResponseBody, Bitmap>() {
                                @Override
                                public Bitmap apply(@NonNull ResponseBody responseBody) throws Exception {
                                    return BitmapFactory.decodeStream(responseBody.byteStream());
                                }
                            })
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Bitmap>() {
                                @Override
                                public void accept(@NonNull Bitmap bitmap) throws Exception {
                                    holder.setText(R.id.tv_title,storiesList.getTitle())
                                            .setImageBitamp(R.id.iv_img,bitmap);
                                }
    
                            });
                }
            };
            mRecyclerView.setAdapter(mAdapter);
            //设置recyclerview布局管理器
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            mRecyclerView.setLayoutManager(linearLayoutManager);
    
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    
            mAdapter.setOnItemClickListener(new SimpleAdapters.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Toast.makeText(MainActivity.this, "click:" + position, Toast.LENGTH_SHORT).show();
                }
    
                @Override
                public void onItemLongClick(View view, int position) {
                    Toast.makeText(MainActivity.this, "longclick:" + position, Toast.LENGTH_SHORT).show();
                }
            });
        }
        //get data by Retrofit & RxJava
        private void getDataByRetrofit() {
            //主要逻辑
            GetNews getNews = RetrofitManager.getInstance().getRetrofit().create(GetNews.class);
            getNews.getNews()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<entity>() {
    
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
    
                        }
    
                        @Override
                        public void onNext(@NonNull entity entity) {
                            storiesList.addAll(entity.getStories());
                            mAdapter.notifyDataSetChanged();
                        }
    
                        @Override
                        public void onError(@NonNull Throwable e) {
                            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
    
                        @Override
                        public void onComplete() {
    
                        }
                    });
        }
    
    }
    

    Rxjava2给出学者的学习链接
    Retrofit2 完全解析 探索与okhttp之间的关系
    有些问题是1与2的问题
    Rxjava1与Rxjava2比较

    相关文章

      网友评论

        本文标题:Rxjava2+retrofit2基础网络请求

        本文链接:https://www.haomeiwen.com/subject/biydqxtx.html