Rxjava use (i) basic use

Source: Internet
Author: User
Tags iterable throwable

Objective

RxJava and Rxandroid More detailed introduction can refer to this document "for Android developers RxJava detailed"

Basic introduction

Reactivex and RxJava use most of the RxJava explained to Android developers andget started with RxJava , and organize and add some of your own understanding.

What is Reactivex

Reactivex is an API that focuses on asynchronous programming and controlling the flow of observable data (or events). It combines the best ideas of the observer pattern, the iterator pattern, and the functional programming.

Real-time data processing is a common phenomenon, and it is important to have an efficient, clean, and extensible way to handle these scenarios. Use observables and Operators to skillfully manipulate them. Reactivex provides a composable and flexible API to create and process data streams, while simplifying some of the concerns of asynchronous programming, such as threading creation and concurrency issues.

RxJava Introduction

Rxjava is an open source implementation of Reactivex on Java. Rxjava can easily handle the framework of background threads or UI thread tasks under different operating environments. The asynchronous implementation of RxJava is achieved through an extended observer pattern.

Observable (observers, or observers) and Subscriber (subscribers) are the two main classes. On RxJava, a Observable is a class that emits a stream of data or an event, and Subscriber is a class that processes (takes action) the emitted items (data streams or events).

   Observable   observer     subscribe ()   method to implement the subscription relationship . A Observable standard stream emits one or more item, then completes successfully or fails. A Observable can have more than one subscribers, and with each item emitted by Observable, the item will be sent to the Subscriber.onnext () method for processing. Once Observable no longer issues items, it will call the Subscriber.oncompleted () method, or Observable will call the Subscriber.onerror () method if there is an error.

OnNext (): RxJava Event callback method, for normal events.

OnCompleted (): Event queue end. RxJava not only handles each event separately, but also considers them as a queue. RxJava requires that the oncompleted () method be triggered as a flag when no new OnNext () is emitted.

OnError (): Event queue exception. When an exception occurs during the event processing, the OnError () is triggered and the queue is automatically terminated, and no more events are allowed to be emitted.

In a properly-run sequence of events, oncompleted () and OnError () have only one, and are the last in the sequence of events. It is important to note that both oncompleted () and OnError () are mutually exclusive, that is, one is called in the queue and no other should be called.


Figure 1-rxjava The Observer pattern ( from "RxJava to Android Developers")

Rxandroid is the Rxjava version added to the Android platform, and a Rxjava package is also required to use rxandroid.

GitHub address and as introduction dependency

GitHub Links:

Https://github.com/ReactiveX/RxJava

Https://github.com/ReactiveX/RxAndroid

Introduce dependencies:

Compile ' io.reactivex:rxandroid:1.1.0 '

Compile ' io.reactivex:rxjava:1.1.0 '

Basic use 1. Create Subscriber (Observer)

Subscriber is an abstract implementation of the observer interface, and it is recommended to use subscriber, which in fact Rxjava Subscibe into a observer during the subscriber process.

Final subscriber<string> tempsubsciber = new Subscriber<string> () {
@Override
public void oncompleted () {
LOG.D (TAG, "oncompleted ()");
}

@Override
public void OnError (Throwable e) {
LOG.D (TAG, "OnError () e=" + e);
}

@Override
public void OnNext (String s) {
LOG.D (TAG, "OnNext () data=" + s);
}
}


2. Create observable
observable<string> tempobservable = observable.create (new observable.onsubscribe<string> () {
@Override
public void call (SUBSCRIBER<? Super String> Subscriber) {
Subscriber.onnext ("01");
Subscriber.onnext ("02");
Subscriber.onnext ("03");


Subscriber.oncompleted ();
}
});

3. Subscribe (subscription)
Tempobservable.subscribe (Tempsubsciber);

Subscribe () mainly did a bit of work:

1) Call Subscriber.onstart ().

2) Call Onsubscribe.call (subscriber) in Observable. To handle the logic of sending events, in RxJava, observable does not start sending events as soon as it is created, but when it is subscribed, when the subscribe () method executes.

3) Return the incoming subscriber as Subscription. This is to facilitate unsubscribe ().

4. Other simple ways of using 1) Quick Create observable

Just (T ...): sends the passed-in parameters sequentially.

Final Observable Observable = Observable.just ("Info1", "Info2", "Info3");


From (t[])/from (ITERABLE<? extends t>): After splitting the incoming array or iterable into specific objects, send them in turn.

Final string[] Infos = {"Info1", "Info2", "Info3"};
Final Observable Observable = Observable.from (infos);

2)SubscribeIncomplete -defined callbacks
Final Action0 oncompletedaction = new Action0 () {
@Override
public void call () {
Equivalent to subscriber's oncompleted ()
}
};


Final action1<string> onnextaction = new Action1<string> () {
@Override
public void Call (String s) {
Equivalent to subscriber OnNext (sring s)
}
};


Final action1<throwable> onerroraction = new Action1<throwable> () {
@Override
public void Call (Throwable throwable) {
Equivalent to subscriber onerror (Throwable e)
}
};


Create subscriber automatically, and use Onnextaction to define ONNEXT ()
Observable.subscribe (onnextaction);
Automatically create subscriber and use Onnextaction and onerroraction to define OnNext () and OnError ()
Observable.subscribe (Onnextaction, onerroraction);
Automatically create subscriber and use Onnextaction, onerroraction, and oncompletedaction to define OnNext (), OnError (), and oncompleted ()
Observable.subscribe (Onnextaction, onerroraction, oncompletedaction);

Here, you can use Rxjava in the simplest way.

5.Cancel Subscription-Unsubscribe ()

The return value of Observable.subscribe () is a Subscription object. The Subscription class has only two methods, unsubscribe () and isunsubscribed ().

Unsubscribe () This method is important, because after subscribe (), Observable will hold a subscriber reference, if not released in time, there will be a risk of memory leaks.

To prevent possible memory leaks, use subscription.isunsubscribed () to check your Subscription as soon as possible in the right place (e.g. OnPause () onStop () OnDestroy, etc.) when you are no longer using it. Whether it is unsubscribed, if not, you can unsubscribe through Subscription.unsubscribe (), Subscriber will no longer receive events.

If Subscription.unsubscribe () is called, Unsubscribing will stop notifying you of the items Subscriber and allow the garbage collection mechanism to release the object, preventing any RxJava from causing a memory leak.

If you are working with multiple observables and subscribers, all Subscription objects can be added to Compositesubscription, and then you can use the Compositesubscription.unsubscribe () method to unsubscribe at the same time (unsubscribed).

Rxjava use (i) basic use

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.