Android RxJava+Retrofit异步网络加载框架
RxJava: 一个在Java vm上使用可观测的序列来组成异步的,基于事件的程序的库。(这是github上的翻译) 现在,这个Rxjava框架基本上取代了AsyncTask和Handler, 因为
AsyncTask和handler的异步加载会随着逻辑的加深,变得越来越复杂(指的是逻辑),而RxJava不会,RxJava是通过一种扩展的观察者模式来实现的,Observabl(被观察者)Observer(观察者) 鼠标subscribe(订阅者) 通过这三个步骤来实现的,下面我将列出代码:就可以清晰看到了。
Retrofit: 这是一个不错的网络加载库,就是对Okhttp的再次封装。Retrfit与OKhttp共同出资square公司,与OK不同的事retrfit需要定义一个接口,用来返回我们的call对象,retrfit提供的请求方式为注解方式,有get和post。参数也是注解的方式,retrfit是square公司开源的一个高质量高效率的http库,它将我们自己开发的底层代码和细节封装了起来。
该项目所需要的依赖包:
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'io.reactivex:rxjava:1.1.6' compile 'io.reactivex:rxandroid:1.2.1' compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
import java.util.HashMap; import retrofit2.http.POST; import retrofit2.http.Query; import retrofit2.http.QueryMap; import rx.Observable; public interface CaipuApi { @POST("/cook/query.php") ObservableCaiPugetCaiPu(@QueryMap HashMap ,String> map); }
import java.util.List; public class CaiPu { private String resultcode; private String reason; private ResultBean result; private int error_code; public String getResultcode() { return resultcode; } public void setResultcode(String resultcode) { this.resultcode = resultcode; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public ResultBean getResult() { return result; } public void setResult(ResultBean result) { this.result = result; } public int getError_code() { return error_code; } public void setError_code(int error_code) { this.error_code = error_code; } public static class ResultBean { private String totalNum; private int pn; private int rn; private ListRxJavaRetrofitUtils(网络操作的一个工具类)data; public String getTotalNum() { return totalNum; } public void setTotalNum(String totalNum) { this.totalNum = totalNum; } public int getPn() { return pn; } public void setPn(int pn) { this.pn = pn; } public int getRn() { return rn; } public void setRn(int rn) { this.rn = rn; } public List getData() { return data; } public void setData(List data) { this.data = data; } @Override public String toString() { return "ResultBean{" + "totalNum='" + totalNum + '\'' + ", pn=" + pn + ", rn=" + rn + ", data=" + data + '}'; } public static class DataBean { private String id; private String title; private String tags; private String imtro; private String ingredients; private String burden; private List albums; private List steps; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getImtro() { return imtro; } public void setImtro(String imtro) { this.imtro = imtro; } public String getIngredients() { return ingredients; } public void setIngredients(String ingredients) { this.ingredients = ingredients; } public String getBurden() { return burden; } public void setBurden(String burden) { this.burden = burden; } public List getAlbums() { return albums; } public void setAlbums(List albums) { this.albums = albums; } public List getSteps() { return steps; } public void setSteps(List steps) { this.steps = steps; } public static class StepsBean { /** * img : http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/90/8963_f58b8378c3c7bc50.jpg * step : 1.鸡腿去骨,肉腌制 */ private String img; private String step; public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getStep() { return step; } public void setStep(String step) { this.step = step; } } } } @Override public String toString() { return "CaiPu{" + "result=" + result.toString() + '}'; } }
import java.util.HashMap; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; public class RxJavaRetorfitUtils { private static RxJavaRetorfitUtils utils=new RxJavaRetorfitUtils(); CaipuApi caipuApi; public static RxJavaRetorfitUtils getInstens(){ return utils; } public RxJavaRetorfitUtils(){ OkHttpClient client=new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS) .build(); Retrofit retrofit=new Retrofit.Builder() .baseUrl("http://apis.juhe.cn/") .client(client) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); caipuApi = retrofit.create(CaipuApi.class); } //提供的方法让使用者去调用 public void getCaiPu(HashMap map, final CallBack call){ ObservableMainActivitycaipu=caipuApi.getCaiPu(map); //调度线程 caipu.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1 () { @Override public void call(CaiPu caiPu) { //可以在里面进行操作 if(null==caiPu){ call.onError(); }else{ call.onSuccess(caiPu); } } }); } //这是一个回调借口 public interface CallBack{ void onSuccess(CaiPu caiPu); void onError(); } }
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import java.util.HashMap; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initPostUrl(); } private void initPostUrl() { HashMap,String> map=new HashMap<>(); map.put("menu","土豆丝"); map.put("key","请求的key值"); RxJavaRetorfitUtils.getInstens().getCaiPu(map, new RxJavaRetorfitUtils.CallBack() { @Override public void onSuccess(CaiPu caiPu) { Toast.makeText(MainActivity.this, caiPu.toString(), Toast.LENGTH_SHORT).show(); } @Override public void onError() { Log.e("aaaa","打印失败"); } }); } }