Using EventBus to Transfer Data

On 2015/12/02 at 23:17

When developing Android apps, it is common to use intent to transfer objects between different components in the same app. For example:

Intent it = new Intent(this, TargetActivity.class);
it.putExtra("key", value);
startActivity(it);

However, this method comes with two problems. First, the object to be transfered needs to be Parceble. Second, if you are passing a big object or multiple objects, passing data though IPC is slow and inefficient.

How does startActivity works?

Whenever you call startAcitvity, you are actually calling startActivity method in AMS(ActivityManagerService) through binder IPC. Binder is an RPC(Remote Procedure Call) mechanism, binder servers(ie. ActivityManagerService) expose their method for client to use. And the data to be transfered is carried by Parcel. Intent called writeToParcel to write all its data into a parcel and then transfer it into the AMS. So the whole procedure works like this, app opened /dev/binder, binder driver uses copy_from_user to copy the data to be transfered into binder driver, AMS uses mmap call to binder device to access the page that contains the data. Then AMS starts the targetActivity and uses the same way to send the data into the targetActivity.

Passing data in the same app through IPC is very weird and slow

Different components in the same app are reside in the same process(unless you specify process attribute in the xml), so we don't need to use IPC the transfer the data. So a common model is using Application Singleton to access data. For example:

// srcActivity
getApplication().xxxData = data;
startActivity(new Intent(this, TargetActivity.class));

// targetActivity
data = getApplication().xxxData

This approach is fast and easy, however when the project comes big, managing all the field in the Application object may be messy.

Here comes to EventBus

EventBus is made by greenrobot. Greenrobot has another very useful project called greenDAO which is a easy-to-use ORM library for android developers to manipulate database in a very simple way(Just like ORM in Django and other popular frameworks). EventBus can let you transfer data between different components(in the same app/process) in a very fast and bautiful way. You can take a look at their docs and I am sure you will love it:).

Comments