通过EventBus对服务和fragment通信的实践

1 EventBus

简单来说,eventbus是一种应用内广播的简易版,可以把数据在activity,service,fragment之间传递,并且代码极易实现

2 构想

之前全部使用了okhttp在各个viewmodel里,使用观察者模式进行数据沟通,但是问题是父子fragment的数据共用问题,以及每次都需要编写网络请求逻辑会造成浪费
经过统计,网络请求包含4种
1 get请求,可封装,返回请求结果
2 get with cookie 可封装 返回请求结果
3 post 只有登录用到了,但返回的不仅需要结果还需要返回的header来把cookie存起来
4 post with cookie 上传文件的逻辑复杂,需要单独编写逻辑

3架构

基于此,构建了service,在单activity启动时将其绑定,然后通过eventbus接受和发送网络请求的结果,在service维护一个线程池,便于提升性能。
okhttp封装如下


```java
public class WebHelper{
    //必须在子线程运行,非子线程运行会报错
    public static MediaType jsonmediaType = MediaType.parse("application/json");
    private static WebHelper webHelper;
    private WebHelper(){}
    public OkHttpClient client = new OkHttpClient();
    public static synchronized WebHelper getInstance(){
        if(webHelper==null)webHelper=new WebHelper();
        return webHelper;
    }
    public static String getInfo(String url) throws IOException {
        Request request=new Request.Builder().url(url).build();
        Response response=WebHelper.getInstance().client.newCall(request).execute();
        return response.body().string();
    }
    public static String getInfoWithCookie(String url,String cookie) throws IOException {
        Request request=new Request.Builder().url(url).header("Cookie",cookie).build();
        Response response=WebHelper.getInstance().client.newCall(request).execute();
        return response.body().string();
    }
    public static String postInfo(String url, RequestBody body) throws  IOException{
        Request request=new Request.Builder().url(url).post(body).build();
        Response response=WebHelper.getInstance().client.newCall(request).execute();
        return response.body().string();
    }
    public static String postWithCookie(String url, RequestBody body,String cookie) throws IOException {
        Request request=new Request.Builder().url(url).header("Cookie",cookie).post(body).build();
        Response response=WebHelper.getInstance().client.newCall(request).execute();
        return response.body().string();
    }
    public static RequestBody SetJSonBody(JSONObject object){
        return RequestBody.create(jsonmediaType,object.toString());
    }
    public static String getCookie(Context context){
        SharedPreferences Infos = context.getSharedPreferences("data", Context.MODE_PRIVATE);
        return Infos.getString("cookie","");
    }
    public static void setCookie(Context context,String cookie){
        SharedPreferences Infos = context.getSharedPreferences("data", Context.MODE_PRIVATE);
        Infos.edit().putString("cookie",cookie).apply();
    }
}

由服务持有这些请求

private Runnable setInforunnable(String url){
       return new Runnable(){
            @Override
            public void run() {
                try {
                    String res=WebHelper.getInfo(url);
                    EventBus.getDefault().post(new ResultMessage(res));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
    }
    private Runnable setStaterunnable(String url,String cookie){
        return new Runnable(){
            @Override
            public void run() {
                try {
                    String res=WebHelper.getInfoWithCookie(url,cookie);
                    EventBus.getDefault().post(new loginstatemessage(res));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
    }
    private Runnable postRunnable(String url, RequestBody body){
        return new Runnable() {
            @Override
            public void run() {
                try {
                    String res=WebHelper.postInfo(url,body);
                    EventBus.getDefault().post(new PostResultMessage(res));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
    }
    private Runnable postRunnableWithCookie(String url,String cookie,RequestBody body){
        return new Runnable() {
            @Override
            public void run() {
                try {
                    String res=WebHelper.postWithCookie(url,body,cookie);
                    EventBus.getDefault().post(new PostResultMessage(res));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
    }
最后通过@Subscribe的注解接受和发送请求
个人认为封装之后可以少写很多重复代码,使用viewmodel解耦的同时还可以减少网络请求次数。
原创文章 6 获赞 0 访问量 1510

猜你喜欢

转载自blog.csdn.net/xxy41092/article/details/106118149