Android Rxbus Event Bus

Source: Internet
Author: User

My Video course: "FFmpeg to build Android Universal Audio Player"

Recently used in the project Rxjava and Rxandroid, really feel pretty good, and then heard that you can use Rxbus to replace the Eventbus and other events distribution of the tripartite library, and then the morning to find a better Rxbus Open source project (think there is a unified standard), but later know, Rxbus no absolute, just an idea, with the help of rxjava characteristics to achieve. In this way, I also implemented a (can set tag, and specify the type of event received), the test results are pretty good. First look at the effect of the picture:


On the way, the event is sent in the first activity, the event is received, the text box contents are changed, the second activity is opened, and the same tag event is sent, so the event sent by the second activity is also received in the first.

First: To add a dependent library

dependencies {
    compile ' io.reactivex:rxjava:1.1.0 '
    compile ' io.reactivex:rxandroid:1.1.0 '
}
II: Writing Rxbus class

Package com.ywl5320.rxbusdemo.RxBus;
Import Java.util.HashMap;

Import Java.util.Map;
Import Rx.android.schedulers.AndroidSchedulers;
Import Rx.functions.Action1;
Import Rx.schedulers.Schedulers;
Import Rx.subjects.PublishSubject;
Import Rx.subjects.SerializedSubject;

Import Rx.subjects.Subject;
 /** * Created by YWL on 2016/5/20. * * Public class Rxbus {private Final subject<object, object> _bus = new Serializedsubject<> (publishsubje
    Ct.create ());

    Private final map<string, object> tags = new hashmap<> ();

    private static Rxbus Rxbus;
                public static Rxbus getinstance () {if (Rxbus = null) {synchronized (Rxbus.class) {
                if (Rxbus = = null) {Rxbus = new Rxbus ();
    }} return Rxbus; /** * Send event message * @param tag is used to differentiate event * @param object event parameters/public void post (String tag, obje CT object) {_BUS.ONNext (object);
        if (!tags.containskey (tag)) {Tags.put (tag, object); /** * @param tag * @param rxbusresult/public void toobserverableonmainthr in main thread EAD (final String tag, final Rxbusresult Rxbusresult) {_bus.observeon (Androidschedulers.mainthread ()). Subscri
                    Be (new action1<object> () {@Override public void call (Object o) {
                    if (Tags.containskey (tag)) {Rxbusresult.onrxbusresult (o);
    }
                }
            }); * @param tag * @param rxbusresult/public void Toobserverablechildthread (Fin/** * child thread) Al String tag, final Rxbusresult Rxbusresult) {_bus.observeon (Schedulers.io ()). Subscribe (New ACTION1&LT;OBJECT&G
                    t; () {@Override public void call (Object o) {if (Tags.containskey (tag)) { RxbusreSult.onrxbusresult (o);
    }
            }
        }); /** * Remove tag * @param tag/public void removeobserverable (String tag) {if tags
            . ContainsKey (tag)) {Tags.remove (tag);
        }/** * When exiting the application, empty the resource */public void release () {tags.clear ();
    Rxbus = null;
 }

}

In the Rxbus class, the subject quote on the Internet was used to explain: "Subject in Reactivex as a bridge or proxy for observer and observerable." Because it is an observer, it can subscribe to one or more observable objects, and because he is an observable object, it can pass and release the data objects it observes and can release new objects. ”

Subject represents an object that is both observable and observer, so subject can use this feature to send and receive messages, even if subscribers are observers. The OnNext (Object) method of subject sends events to all subscribers, but we are generally in the project is point-to-point send, do not want other unrelated subscribers also receive events, so in Rxbus added a map to manage the event tag, to distinguish the event from where , going where.

To write less code to receive, a callback function is written to handle the received information:

Package com.ywl5320.rxbusdemo.RxBus;

/**
 * Created by YWL on 2016/5/20.
 * * Public
interface Rxbusresult {

    /**
     * Event Callback Interface
     * @param o
    /void Onrxbusresult (Object o);



Two: How to use

1, first define Rxbus and initialize

Private Rxbus Rxbus = Rxbus.getinstance ();
2, send the message

Btnsend.setonclicklistener (New View.onclicklistener () {
            @Override public
            void OnClick (View v) {
                Rxbus.post ("A", New String ("Hello Rxbus");
            }
        );
Where "First" is the tag that distinguishes the event, and the second parameter is the object that is sent.

3. Receive Message

Rxbus.toobserverableonmainthread ("A", new Rxbusresult () {
            @Override public
            void Onrxbusresult (Object o) {
                final String msg = (string) o;
                Mtvmsg.settext ("I received the message;" + msg);
                Toast.maketext (Mainactivity.this, "received the message;" + MSG, Toast.length_short). Show ();
            }
        
This specifies that messages in the main thread receive tag "a" and are processed.

This is done to send and receive, but in order to better manage the tag, we are best to exit the corresponding tag to clear out, such as:

@Override
    protected void OnDestroy () {
        Super.ondestroy ();
        Rxbus.removeobserverable ("a");
    

Finally: the Rxbus.release () method is also required to release resources when the application is completely exited (and also to avoid a problem: If you do not release, you cannot update the UI the second time you start the application, possibly because the Rxbus and second boot applications are not in the same process. Because the first time to quit the application, the Rxbus is not destroyed, the second will not be recreated, so that caused the problem.

Finally put the mainactivity and secondactivity code out:

Package Com.ywl5320.rxbusdemo;
Import android.content.Intent;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.TextView;

Import Android.widget.Toast;
Import Com.ywl5320.rxbusdemo.RxBus.RxBus;

Import Com.ywl5320.rxbusdemo.RxBus.RxBusResult;
    public class Mainactivity extends Appcompatactivity {private Button btnsend;
    Private Button Btnsecond;

    Private TextView mtvmsg;

    Private Rxbus Rxbus = Rxbus.getinstance ();
        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

        Setcontentview (R.layout.activity_main);
        Btnsend = (Button) Findviewbyid (r.id.btn_send);
        Btnsecond = (Button) Findviewbyid (R.id.btn_second);

        Mtvmsg = (TextView) Findviewbyid (r.id.tv_msg); Btnsend.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v){Rxbus.post ("a", New String ("Hello Rxbus"));

        }
        });
                Btnsecond.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
                Intent Intent = new Intent (mainactivity.this, Secondactivity.class);
            MainActivity.this.startActivity (Intent);

        }
        }); Rxbus.toobserverableonmainthread ("A", new Rxbusresult () {@Override public void Onrxbusresult (
                Object o) {final String msg = (String) o;
                Mtvmsg.settext ("I received the message;" + msg);
            Toast.maketext (Mainactivity.this, "received the message;" + MSG, Toast.length_short). Show ();

        }
        }); Rxbus.toobserverableonmainthread ("Second", New Rxbusresult () {@Override public void Onrxbusresult (Object o)
                {String msg = (string) o;
            Mtvmsg.settext ("second received the message;" + msg);    Toast.maketext (Mainactivity.this, "second received the message;" + MSG, Toast.length_short). Show ();

    }
        });
        /** * Exit, Release Rxbus/@Override protected void OnDestroy () {Super.ondestroy ();
    Rxbus.release ();
 }
}

Package Com.ywl5320.rxbusdemo;
Import Android.os.Bundle;
Import android.support.annotation.Nullable;
Import android.support.v7.app.AppCompatActivity;
Import Android.view.View;

Import Android.widget.Button;

Import Com.ywl5320.rxbusdemo.RxBus.RxBus;
 /** * Created by YWL on 2016/5/20.
    * * public class Secondactivity extends Appcompatactivity {private Button mbtnsend;

    Private Rxbus Rxbus = Rxbus.getinstance ();
        @Override protected void OnCreate (@Nullable Bundle savedinstancestate) {super.oncreate (savedinstancestate);

        Setcontentview (r.layout.second_activity);
        Mbtnsend = (Button) Findviewbyid (r.id.btn_send);
                Mbtnsend.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
            Rxbus.post ("Second", New String ("Data for second page"));

    }
        });
        } @Override protected void OnDestroy () {Super.ondestroy ();
Rxbus.removeobserverable ("a");    }
}
 

This completes the Rxbus tool class to write demo download address (Note: Demo Rxbus have bugs, is not at the same time two receive the same message sent, here can be the blog, the blog has been modified, you can compare what Yo ha hahaha).

Github:https://github.com/wanliyang1990/rxbusdemo









Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.