Eventbus tutorial

Eventbus tutorial

Summary
eventbus official api document
eventbus download address

eventbus official api documentation

1. Eventbus configuration

2. Eventbus source code analysis (#Eventbus source code analysis)

3. Eventbus tutorial

Eventbus configuration

Add dependencies in the dependencies {} module of the gradle file

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation group: 'org.greenrobot', name: 'eventbus', version: '3.1.1'
}



Eventbus tutorial

1. Custom event class (essentially a java bean class, used to define the type of data transmitted)

public class MyEvent {
    String message;
    public MyEvent(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

2. Register and unregister events in the specific implementation class of subject

Taking activity as an example, when we need to subscribe to events in Activity or Fragment, we need to register EventBus. We generally choose to register EventBus in the onCreate () method of Activity, and deregister in the onDestory () method.

Registration issue

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.testBtn);
        button.setOnClickListener(this);
        tv = (TextView)findViewById(R.id.txt);
        //注册observer
        EventBus.getDefault().register(this);
    }

Logout event

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

3. Send events

Can be placed in any desired position, here is an example of triggering event sending after clicking the button

    @Override
    public void onClick(View v) {
        EventBus.getDefault().post(new MyEvent("nice to meet you"));
    }

4. Event processing

The method annotated with @Subscribe is the event handler. The method name for processing messages is unlimited, but you need to specify the thread model.

Threading model

  • ThreadMode.MAIN Event handler methods are called in a separate thread.
  • ThreadMode.ASYNC
  • ThreadMode.BACKGROUND
  • ThreadMode.MAIN_ORDERED
  • ThreadMode.POSTING
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void subscribeMyEvent(MyEvent event){
        tv.setText(event.getMessage());
    }

Eventbus source code analysis

Eventbus using the Observer pattern
Top click to jump

Guess you like

Origin www.cnblogs.com/peter-dev/p/10686698.html