Getting Started with the RxJava

Source: Internet
Author: User
Tags throwable

First, what is RxJava?

RxJava is a responsive programming framework that uses the observer design pattern. So naturally there are Observable and subscriber these two things.

RxJava is an open source project, address: Https://github.com/ReactiveX/RxJava

There is also a rxandroid, used for Android development, adding an interface for Android. Address: Https://github.com/ReactiveX/RxAndroid

Ii. examples

Return weather data by requesting the Openweathermap weather query interface

1. Increase compilation dependency

1 Dependencies {2     ' Libs ', include: [' *.jar '])3     ' com.android.support:appcompat-v7 : 22.0.0 '4     ' io.reactivex:rxjava:1.0.9 '5     ' Io.reactivex: rxandroid:0.24.0 '6     ' com.squareup.retrofit:retrofit:1.9.0 '7 }

Retrofit is a restful request client. See: http://square.github.io/retrofit/

2. Server interface

1 /**2 * Interface3 * Created by Hal on 15/4/26.4  */5  Public classApimanager {6 7     Private Static FinalString ENDPOINT = "http://api.openweathermap.org/data/2.5";8 9     /**Ten * Service Interface One      */ A     Private InterfaceApimanagerservice { -@GET ("/weather") -Weatherdata GetWeather (@Query ("Q") String Place, @Query ("units") String units); the     } -  -     Private Static FinalRestadapter Restadapter =NewRestadapter.builder (). setEndPoint (ENDPOINT). Setloglevel (RestAdapter.LogLevel.FULL). build (); -  +     Private Static FinalApimanagerservice Apimanager = Restadapter.create (apimanagerservice.class); -  +     /** A * The data returned by the service interface is encapsulated into {@linkRx. Observable} at      * @param City -      * @return -      */ -      Public StaticObservable<weatherdata> Getweatherdata (FinalString City) { -         returnObservable.create (NewObservable.onsubscribe<weatherdata>() { - @Override in              Public voidCall (SUBSCRIBER&LT;?SuperWeatherdata>subscriber) { -                 //subscribers callback OnNext and oncompleted toSubscriber.onnext (Apimanager.getweather (City, "metric"))); + subscriber.oncompleted (); -             } the }). Subscribeon (Schedulers.io ()); *     } $}

The subscriber's callback has three methods, onnext,onerror,oncompleted

3. Interface invocation

1   /**2 * Multiple City requests3 * Map,flatmap transforms the observable4          */5Observable.from (CITIES). FlatMap (NewFunc1<string, observable<weatherdata>>() {6 @Override7              PublicObservable<weatherdata>Call (String s) {8                 returnApimanager.getweatherdata (s);9             }Ten }). Subscribeon (Schedulers.io () ) One . Observeon (Androidschedulers.mainthread ()) A. Subscribe (/*OnNext*/NewAction1<weatherdata>() { - @Override -                      Public voidCall (Weatherdata weatherdata) { the log.d (Log_tag, weatherdata.tostring ()); -                     } -},/*OnError*/NewAction1<throwable>() { - @Override +                      Public voidCall (Throwable throwable) { -  +                     } A                 }); at  -         /** - * Single City request -          */ -Apimanager.getweatherdata (cities[0]). Subscribeon (Schedulers.io () ) - . Observeon (Androidschedulers.mainthread ()) in. Subscribe (NewAction1<weatherdata>() { - @Override to                      Public voidCall (Weatherdata weatherdata) { + log.d (Log_tag, weatherdata.tostring ()); - ((TextView) Findviewbyid (R.id.text)). SetText (Weatherdata.tostring ()); the                     } *},NewAction1<throwable>() { $ @OverridePanax Notoginseng                      Public voidCall (Throwable throwable) { - log.e (Log_tag, Throwable.getmessage (), throwable); the                     } +                 }); A  the         /** + * Android View event handling -          */ $Viewobservable.clicks (Findviewbyid (R.id.text),false). Subscribe (NewAction1<onclickevent>() { $ @Override -              Public voidCall (Onclickevent onclickevent) { -  the             } -});

Subscribeon (Schedulers.io () ) and Observeon (Androidschedulers.mainthread ( )) define the threads for each of these two actions. Android UI updates are required on the main thread.

4, Retrofit support Rxjava integration

1 /**2 * Service Interface3      */4     Private InterfaceApimanagerservice {5@GET ("/weather")6Weatherdata GetWeather (@Query ("Q") String Place, @Query ("units") String units);7 8         /**9 * Retrofit supports Rxjava integrationTen * This method is suitable for new interfaces One          */ A@GET ("/weather") -Observable<weatherdata> Getweatherdata (@Query ("Q") String Place, @Query ("units") String units); -}

Demo Code

--------EOF-----

Getting Started with the RxJava

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.