Android's Rxbus detailed

Source: Internet
Author: User
Tags eventbus

2016, rxjava/rxandroid Fire, many people have joined the ranks of responsive programming, today we come to talk about Rxbus

Before we wanted to pass information between activity or fragment, we would receive information through Onactvityresult. But there is a drawback, one is that the amount of code is too large, the repetition rate is too high. Second, there are times to pass the data need to go through a number of interface jump. Add some information from the A->b->c,c interface, while also trying to refresh the interface on the A interface. Then it is difficult to operate through Onactvityresult. Also, add a message from the A->B,B to the A interface. In the past through Onactvityresult, we need the B interface to be closed, a interface to get the data, and then local refresh, so that the A interface is likely to flicker (data refresh). In this way, the user experience is very poor. So now, what can we do?

Before using Rxjava, I use Eventbus to communicate between components. Today we are not talking about Eventbus, we are speaking about Rxbus.

First of all, we'd better take a look at Rxjava, the following is a simple introduction:

Introduction reprinted from:

http://www.imooc.com/article/2298

Code ideas come from:

Http://www.jianshu.com/p/ca090f6e2fe2

Rxjava is an open-source implementation of Reactivex in Java. Observable (Observer) and Subscriber (Subscriber) are the two main classes. On Rxjava, a observable is a class that emits data streams or events, and Subscriber is a class that handles (acts) the items that are emitted (data flows or events). A observable standard stream emits one or more item and then completes successfully or fails. A observable can have multiple subscribers, and each item that is emitted by observable will be sent to the Subscriber.onnext () method for processing. Once observable no longer issues items, it will call the Subscriber.oncompleted () method, or if there is an error observable will invoke the Subscriber.onerror () method.

First, attach rxjava/rxandroid links, or go directly to GitHub search to see the latest version of the link

Compile ' io.reactivex:rxjava:1.1.0 '
compile ' io.reactivex:rxandroid:1.1.0 '

Nonsense not much to say, directly attached Rxbus code

public class Rxbus {private static volatile rxbus defaultinstance;
    Private final subject<object, Object> bus; Publishsubject will only transmit data from the original observable after the point at which the subscription occurred to the Observer public Rxbus () {bus = new serializedsubject<> (Pu
    Blishsubject.create ()); ///Single example Rxbus public static Rxbus Getdefault () {if (defaultinstance = = null) {synchronized (R)
                Xbus.class) {if (defaultinstance = = null) {defaultinstance = new Rxbus ();
    }} return defaultinstance;
    //Send a new event public void post (Object o) {bus.onnext (o); The Observer public <T> observable<t> toobservable of a particular type (EventType) are returned based on the passed EventType type (class<t> E Venttype) {return Bus.oftype (EventType)//Here Thanks for the little tang reminder: OfType = filter + cast//return Bus.filter (New Func1<object, boolean> () {//@Override//Public BOolean call (Object o) {//return eventtype.isinstance (o);//}//}). Cast (EventType); }
}

The code is simple, first creating a single instance of the Rxbus object, and then sending an event by post, the initiator as an observer. Or observe an event through toobservable.

Here's an explanation. Rxjava generally has three kinds of action: Onnext,oncomplete,onerror. Corresponding to the next action, as well as the completion of the action, the action when the error.

Public observable toobservable (Class eventtype)
This passes through the generic to an object and then observes the object.

Now it's time to introduce the code to how to initiate a thing.

public class User {

    private String username;
    private String password;

    Public String GetUserName () {return
        username;
    }

    public void Setusername (String username) {
        this.username = username;
    }

    Public String GetPassword () {return
        password;
    }

    public void SetPassword (String password) {
        this.password = password;
    }

    Public User (string Username, string password) {
        this.username = Username;
        This.password = password;
    }

User user = new user ("Pan Rui Jay", "123456");
Rxbus.getdefault (). Post (user);

First, we want to create a new user object as the data we want to send out.
Then the new object is passed through Rxbus.getdefault (). Post (), and the data is sent out, so at this point, a notification is received for the event subscription. In fact, Rxjava is an implementation of the observer pattern.

So, let's take a look at how we receive the data, the code reads as follows:

Rxbus.getdefault (). toobservable (User.class)
                //Subscribe to IO threads to perform some time-consuming operations
                . Subscribeon (Schedulers.io ())
                / /The main thread to observe, you can do UI update operations
                . Observeon (Androidschedulers.mainthread ())
                //Observed objects
                . Subscribe (user->{
                    // Gets an object, user                 Toast.maketext (this,user.getusername (), Toast.length_short). Show ();
                

I used the lambda expression for shorthand when I looked at the object, which is a new feature of JAVA8, interested to know, and some operators, such as Map,flatmap,filter,zip and so on, here is no demo.

Here the code effect and the above code is the same, if you use Java8 friend, in the new Action1 () Here Click Alt+enter, you can simplify the code.

Rxbus.getdefault (). toobservable (Invitationmessage.class)
                //Subscribe to IO threads to perform some time-consuming operations
                . Subscribeon ( Schedulers.io ())
                 ///In the main thread to observe, can do UI update operations
                 . Observeon (Androidschedulers.mainthread ())
                 //object of observation
                . Subscribe (new action1<user> () {
                     @Override public
                     void call (user user) {                toast.maketext. User.getusername (), Toast.length_short). Show ();
                     }
                 };

Some people say that in that case, Rxbus and Eventbus do the same thing. It would be better to use Eventbus directly.

Rx: Function-responsive programming, Eventbus: Event bus
Rxjava mainly do asynchronous, network data processing, powerful is the data processing, and for processing after the data processing is the same observer mode to inform, through the operator can perform chain call, code clear.
Combine retrofit2, make network request, can make network request become very elegant, of course, use rxjava that do not have to import eventbus, that is not the volume is smaller.

As for the use of which, or to see a person's liking it ...

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.