EventBus event bus framework (publisher/subscriber pattern, observer pattern)

1. The way of message passing in android application:
1. Handler way ------- message passing between different threads.
2. Interface interface callback method ------- any two objects.
3. Intent communicates between components and broadcasts.


2. A better way to write a singleton:
private static volatile EventBus defaultInstance;
the constructor should be private, not public

 1 public static EventBus getDefault() {
 2   if (defaultInstance == null) {
 3     synchronized (EventBus.class) {
 4       if (defaultInstance == null) {
 5         defaultInstance = new EventBus();
 6       }
 7     }
 8   }
 9   return defaultInstance;
10 }


The double-checked lock (DCL) method prevents concurrency problems and greatly improves efficiency.

3. Before EventBus 3.0
1. An event framework mechanism designed to simplify the communication between Activity, Fragment, Service, threads, etc. designed by the publisher/subscriber mode (observer mode), which
makes the code concise and less coupled.
2. Main core content: registration (event subscription) method, event publishing method, and anti-registration (unsubscription) method.

3. EventBus gets an instance through DCL singleton EventBus.getDefault();

EventBus provides a total of 4 thread models ThreadModel, namely PostThread, MainThread, BackgroundThread, Async.
PostThread -------------- Default implementation, execution occurs on the same thread that publishes the event;
MainThread -------------- Executes on the UI main thread;
BackgroundThread, Async---both are executed through the Executors.newCachedThreadPool() thread pool.


Event event, any type of object;
subsciber event subscriber,
publisher event publisher, EnentBus.post(Object)

EnventBus.getDefault()
EnventBus.getDefault().register()
EnventBus.getDefault().unregister()
EnventBus.getDefault().post(Object)
Fourth, EventBus 3.0 version introduces annotations to subscribe handler functions that
can be passed through the runtime Annotation + reflection to obtain subscription callback function
You can also generate a class file through the @Subscribe annotation at compile time, and generate the MyEventBusIndex class at compile time, which contains the content of List<SubscriberMethod>.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325121117&siteId=291194637