許小美@Forgame.Taipei
Android的三鐵共構
Eventbus
Android Taipei - Dec 29 2014
Simple Example
- Fragment Activity
- Fragment
- ListView
- Handler
- AsyncTask
Complex Example
- Fragment Activity
- Fragment
- ListView
- Handler
- AsyncTask
- Broadcast
- Service
- etc.
Complex Connect
攏長的 Code 會讓人忘記哪條通道有在使用
就像是還有人認為忠孝西路有公車停靠一般...
為什麼不能簡單點呢!
Pretty Code...
What is Eventbus?
EventBus is publish/subscribe event bus optimized for Android.
Eventbus
Eventbus Component
- Publishers
- Subscribers
- Events
- Bus
EventBus in 4 Steps
- Define an event
Public class MyEvent{} - Register subscriber
EventBus.getDefault().register(this); - Post an event
EventBus.getDefault().post(event); - Receive the event
Public void onEvent(MyEvent event);
Define an event
public class Event {
public static class ItemListEvent {
private List<Item> items;
public ItemListEvent(List<Item> items) {
this.items = items;
}
public List<Item> getItems() {
return items;
}
}
}
register/unregister subscriber
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Register
EventBus.getDefault().register(this);
}
@Override
public void onDestroy() {
super.onDestroy();
// Unregister
EventBus.getDefault().unregister(this);
}
Post an event
// Get listview items data from Network
EventBus.getDefault().post(new ItemListEvent(Item.ITEMS));
Receive the event
public void onEventMainThread(ItemListEvent event) {
setListAdapter(new ArrayAdapter<Item>(getActivity(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1, event.getItems()));
}
- onEventPostThread
- onEventMainThread
- onEventBackgroundThread
- onEventAsync
EventBus Thread Mode
Summary
- Easy use
- Pretty Code
- Observer Pattern
- Performs well with Activities, Fragment, Background threads
Android Taipei - Dec 2014
By Neo Hsu
Android Taipei - Dec 2014
Eventbus with Android
- 1,502