Rx implementation event bus (similar to EventBus) summary

RxBus demo analysis

Label (space separated): RxJava


### Here is the event bus implemented by Rx, similar to EventBus and Otto, using rx implementation, effectively reducing the size of the jar, and using the same as EventBus, is also sending events, The observer then subscribes to the event and responds to it after receiving the event. ###example (not very good here (after all, two activities, better can be passed back)) is used here Login, if the login is successful, send a UserEvent event in the LoginActivity, then register the event in the MAinActivity, and process the event received after registration. LoginActivity.class logic

                                mDataBean = user.getData();
                                if (mDataBean != null){
                                    String username = mDataBean.getUsername();
                                    String imageUrl = mDataBean.getLogo_url();
                                    String useremail = mDataBean.getEmail();
                                    UserEvent event = new UserEvent(username,imageUrl,useremail);
                                    RxBus.getDefault().post(event);
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            mBuilder.build().dismiss();
                                            LoginActivity.this.finish();
                                        }
                                    },500);
                                }
                       
Copy code

Logic in MainActivity.class

 /**
           * Receive events and do related processing
     */
    private void subscribeEvent(){
        RxSubscriptions.remove(mRxSub);
        mRxSub = RxBus.getDefault().toObservable(UserEvent.class)
                .map(new Func1<UserEvent, UserEvent>() {
                    @Override
                    public UserEvent call(UserEvent userEvent) {
                        return userEvent;
                    }
                })
                .subscribe(new RxBusSubscriber<UserEvent>() {
                    @Override
                    public void onEvent(UserEvent userEvent) {
                        if (userEvent != null){
                            mTvEmail.setText(userEvent.mUserEmail);
                            mTvName.setText(userEvent.mUserName);
                            Glide.with(MainActivity.this)
                                    .load(userEvent.mImageUrl).asBitmap()
                            .into(mIvAvator);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

Copy code

Of course, don't forget to register event listeners.

    /*Register to subscribe to the RxBus event*/
        subscribeEvent();
Copy code

can be implemented at this time. When the login is successful, the details such as user name and avatar will be updated. In fact, this logic is still very suitable. After all, if there is a user name and avatar on the left side, If the left side of the title of the homepage is also an avatar, it is still appropriate to use this logic. And the same observer can be subscribed to by multiple observers. The logic code is the same, registering to subscribe to the same observer. ###To be continued (sticky event) Sometimes we may send an event before registering the observer, but if we directly Sending a general event, then since we did not register to receive the event, this time we even received the receiving event, then it is not received, this time we think of sticky events.

Sticky events are like we send at any time. If there are no registrants to receive after sending, they will be cached in a cache, waiting for the observer to receive, and wait until the observer registers to receive and consume. Of course, the sticky event of RxBus will only be consumed by the last saved event.

##### Let's first look at an example below. Here we send a sticky event first, of course, for comparison, our general events and sticky events are triggered when clicked.

 mTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxBus.getDefault().post(new TestEvent("Normal Ceshi"));
                RxBus.getDefault().postSticky(new TestEvent("Sticky Ceshi"));
                startActivity(new Intent(MainActivity.this,TestActivity.class));
            }
        });
Copy code

Of course, although they are triggered, the message we pass is not feasible (for comparison). At this time, we register and receive the observer in the TestActivity after the jump. Let's look at the logic. (Of course, the general registration and the above code are the same, here is not written, directly registered on the sticky event)

 /**
           * Accept sticky events and do related processing
     */
    public void subscribeStickyEvent(){
        if (mRxStickySub != null && !mRxStickySub.isUnsubscribed()){
                         RxSubscriptions.remove(mRxStickySub); //Remove
        } else {
            TestEvent testEvent = RxBus.getDefault().getStickyEvent(TestEvent.class);

            mRxStickySub = RxBus.getDefault().toObservableSticky(TestEvent.class)
                    .map(new Func1<TestEvent, TestEvent>() {
                        @Override
                        public TestEvent call(TestEvent testEvent) {
                            try {
                                                         / / Actively intercept the exception here
                            } catch (Exception e){

                            }
                            return testEvent;
                        }
                    }).subscribe(new RxBusSubscriber<TestEvent>() {
                        @Override
                        public void onEvent(TestEvent testEvent) {
                            Toast.makeText(TestActivity.this, testEvent.test, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                        }
                    });
        }

        RxSubscriptions.add(mRxStickySub);
    }
Copy code

Let's take a look at the renderings.

####Note must be called when the activity or fragment is destroyed.

 @Override
    protected void onDestroy() {
        super.onDestroy();
                 //Remove here. It is also possible to test normal send events. If it is sent before registration, it will not be received.
        RxSubscriptions.remove(mRxSub);
                 //This is ok, the timely event is sent before registration, but the sticky event will remain until there is an observer registration event and receive
        RxSubscriptions.remove(mRxStickySub);
    }
Copy code

Because I didn't call this destruction before (preventing memory leaks), when I clicked on the jump, the general event also appeared in the bullet box, and the sticky event appeared 3 times ((>_<)). Basically, the above can be used for general project usage. ####Code Transfer Gate https://github.com/wuyinlei/RxBus ## ##Thanks to the author Thanks to @YoKey, if you are interested, you can read http://www.jianshu.com/p/ca090f6e2fe2 Thank you again. Here I am just learning the record. Convenient for yourself to find later.

Intelligent Recommendation

Guava: Event Bus EventBus

EventBus literal translation is an event bus, which uses the publish-subscribe model supports communication between components, do not need to explicitly register a callback, more flexible than the ob...

Android event bus: EventBus

Recently another project to maintain, are relatively old variety of libraries used, eventbus using the 2.x version, then upgrade to one, by the way read the next eventbus source, make a note of this: ...

EventBus of Android event bus

First language EventBus is an Android-optimized publish/subscribe message bus, which simplifies communication between components in the application, and between components and background threads. For ...

Event bus: EventBus

When non-parent-child components need to communicate, in addition to vuex, there isEvent busUp Introduction EventBus is also called event bus. In Vue, you can use EventBus as a communication bridge co...

EventBus event processing bus

Write first EventBus is an event processing bus, which can replace Android's traditional Intent, Handler, Broadcast or interface functions to transfer data and execute methods between Fragment, Activi...

More Recommendation

Android EventBus event bus

Android EventBus Preface: Mainly analyze and understand from three aspects: what is EventBus, why use EventBus and how to use EventBus. What is EventBus (what) Why use EventBus (why) How to use EventB...

EventBus 3.0 Event Bus

How to use EventBus 3.0 and some problems encountered during use Hmm~ I am a new Android programmer This is the first article I wrote on the blog, and I finally finished writing with a nervous mood De...

【Event Bus】Analyze EventBus

The above learning is based on the advanced light of Android...

Flutter event bus EventBus

In Android native, there are broadcasts that can transfer data across pages. In Flutter, we can customize an event bus to transfer data across pages. step Define a singleton class Add a Map<String ...

Eventbus event bus

What is Eventbus event bus Eventbus is a message bus that implements the observer mode, used to simplify the components of the program, thread communication, can easily switch threads, open up threads...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top