Android 解耦利器 EventBus

  Andorid 开发过程中总会遇到各个模块耦合问题,使用EventBus是一种解耦方式。

  EventBus 源代码下载地址 https://github.com/greenrobot/EventBus

 

  如果一个ListView展示的内容需要到网络上请求该数据,那么该业务需要如下几个步骤:

1.发送请求拼装URL--->

2.发送请求-->

3.得到数据--->

4.渲染数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//使用传统的Handler和线程
         final Integer GET_DATA= 1001;
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
 
                if(msg.what == GET_DATA){
                    // 做渲染
 
 
                }
            }
        };
 
        new Thread(){
            public void run() {
                //发送HTTP请求得到数据
 
                String result = "";
 
 
                //result = http.get("http://test.com/list");
                Message message = handler.obtainMessage();
                message.getData().putString("result",result);
                message.what = GET_DATA;
                handler.handleMessage(message);
            }
        }.start();
 
 
//使用EventBus
 
 
 
        class ResponseEvent{
            String result;
            ResponseEvent(String result){
                this.result = result;
            }
 
        }
 
        class ResponseErrorEvent{
 
        }
 
        class RequestEvent{
            StringBuffer url=new StringBuffer("http://test.com");
            RequestEvent(String url){
                this.url.append(url);
            }
        }
 
 
        class HttpManager{
 
            //子线程运行
            public void onEventBackgroundThread(RequestEvent request){
                try{
                    String result ="";
                    //开始发送HTTP请求来说去数据
                    //result = http.get(request.url);
 
                    //将获取到的数据发送出去,监听了改Event的地方都可以获取到数据
                    EventBus.getDefault().post(new ResponseEvent(result));
                }catch (Throwable throwable){
                    LogUtil.e(throwable);
                    EventBus.getDefault().post(new ResponseErrorEvent());
                }
 
            }
 
        }
 
        //注册需要事件监听器
        EventBus.getDefault().register(new HttpManager());
 
        //注册需要事件监听器
        EventBus.getDefault().register(this);
 
        EventBus.getDefault().post(new RequestEvent("/list"));
 
        //主线程中运行
        public void onEventMainThread(ResponseEvent responseEvent) {
            //渲染数据
            //responseEvent.result;
 
        }

  

 

posted @   骑着毛驴上京城  阅读(650)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示