Advertisement
Guest User

RxJava Basics

a guest
Feb 28th, 2016
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.00 KB | None | 0 0
  1. package org.rx.java.tutorial;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import rx.Observable;
  7. import rx.Subscriber;
  8. import rx.functions.Func1;
  9.  
  10. public class Main {
  11.  
  12.     // Check this tutorial:
  13.     // http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/
  14.  
  15.     // Dependency for gradle project:
  16.     // compile 'io.reactivex:rxjava:1.1.1'
  17.  
  18.     // ====================================================================
  19.  
  20.     // Key idea #1: Observable and Subscriber can do anything.
  21.  
  22.     // Key idea #2: The Observable and Subscriber are independent of the
  23.     // transformational steps in between them.
  24.  
  25.     // Key idea #3: Operators let you do anything to the stream of data. The
  26.     // only limit is yourself.
  27.  
  28.     // ====================================================================
  29.  
  30.     // Notes:
  31.     // 1. onError() is called if an Exception is thrown at any time.
  32.     // 2. The operators don't have to handle the Exception.
  33.     // 3. You know when the Subscriber has finished receiving items.
  34.     // 4. When you call Observable.subscribe(), it returns a Subscription.
  35.     // 5. RxJava has awesome docs / marble diagrams inside code
  36.     // 6. using unsubscribe will terminate wherever it is currently executing
  37.     // code
  38.     // 7. List of operators:
  39.     // https://github.com/ReactiveX/RxJava/wiki/Alphabetical-List-of-Observable-Operators
  40.  
  41.     public static void main(String[] args) {
  42.  
  43.         // 1. verbose example
  44.         Observable<String> myObservable = Observable.create(new Observable.OnSubscribe<String>() {
  45.             public void call(Subscriber<? super String> sub) {
  46.                 sub.onNext(extracted());
  47.                 sub.onCompleted();
  48.             }
  49.  
  50.             private String extracted() {
  51.                 return "1. Hello, world!";
  52.             }
  53.         });
  54.  
  55.         Subscriber<String> mySubscriber = new Subscriber<String>() {
  56.             public void onCompleted() {
  57.                 System.out.println("1. the end");
  58.             }
  59.  
  60.             public void onError(Throwable e) {
  61.                 System.out.println("error");
  62.             }
  63.  
  64.             public void onNext(String s) {
  65.                 System.out.println(s);
  66.             }
  67.         };
  68.         myObservable.subscribe(mySubscriber);
  69.  
  70.         // 2. almost same thing as above
  71.         Observable.just("2. Hello, world!").subscribe(s -> System.out.println(s + "-Krzysztof"));
  72.  
  73.         // 3. map operator - transforming
  74.         Observable.just("3. Hello, world!").map(s -> s + "-Krzysztof")
  75.                 .subscribe(s -> System.out.println(s));
  76.                 // http://reactivex.io/documentation/operators/map.html
  77.  
  78.         // 4. subscriber receive Integer
  79.         Observable.just("4. Hello, world!").map(s -> s.hashCode())
  80.                 .subscribe(i -> System.out.println("4. " + Integer.toString(i)));
  81.  
  82.         // 5. subscriber shouldn't have much logic so...
  83.         Observable.just("5. Hello, world!").map(s -> s.hashCode()).map(i -> Integer.toString(i))
  84.                 .subscribe(s -> System.out.println("5. " + s));
  85.  
  86.         // 6. some transformations
  87.         Observable.just("6. Hello, world!").map(s -> s + " -Krzysztof").map(s -> s.hashCode())
  88.                 .map(i -> Integer.toString(i)).subscribe(s -> System.out.println("6. " + s));
  89.  
  90.         List<String> arrayList = new ArrayList<String>();
  91.         arrayList.add("Krzysztof");
  92.         arrayList.add("Karol");
  93.         arrayList.add("Irek");
  94.  
  95.         // 7. from operator emits one element each time
  96.         Observable.just(arrayList).subscribe(names -> {
  97.             Observable.from(names).subscribe(name -> System.out.println("7. Name: " + name));
  98.         });
  99.         // http://reactivex.io/documentation/operators/from.html
  100.  
  101.         // 8. list observable transformed into observable which emits single
  102.         // result with after change name, filtering and taking entry at the end
  103.         Observable.just(arrayList).flatMap(names -> Observable.from(names))
  104.                 .flatMap(name -> Observable.just(name + " is awesome"))
  105.                 .filter(nameChange -> !"Karol is awesome".equals(nameChange)).take(1)
  106.                 .subscribe(result -> System.out.println("8. " + result + "- this is the result"));
  107.                 // http://reactivex.io/documentation/operators/flatmap.html
  108.  
  109.         // 9. doOnNext() allows us to add extra behavior each time an item is
  110.         // emitted, in this case singing 'lalala'
  111.         Observable.just(arrayList).flatMap(names -> Observable.from(names))
  112.                 .flatMap(name -> Observable.just(name + " is awesome"))
  113.                 .filter(nameChange -> !"Irek is awesome".equals(nameChange)).take(1)
  114.                 .doOnNext(nameChange -> System.out.println("9. lalalla"))
  115.                 .subscribe(result -> System.out.println("9. " + result + "- this is the result"));
  116.                 // http://reactivex.io/documentation/operators/filter.html
  117.                 // http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnNext(rx.functions.Action1)
  118.  
  119.         // 10. error example
  120.         Observable.just(arrayList).flatMap(names -> Observable.from(names))
  121.                 .flatMap(name -> Observable.just(name + " is awesome"))
  122.                 .filter(nameChange -> getError(nameChange).equals("anything")).take(1)
  123.                 .doOnNext(nameChange -> System.out.println("10. lalalla"))
  124.                 .onErrorReturn(new Func1<Throwable, String>() {
  125.                     @Override
  126.                     public String call(Throwable t) {
  127.                         return "error";
  128.                     }
  129.                 })
  130.                 .subscribe(result -> System.out.println("10. " + result + " - this is the result"));
  131.  
  132.         // 11. Schedulers: easy threading
  133.         // myObservableServices.retrieveImage(url)
  134.         // .subscribeOn(Schedulers.io())
  135.         // .observeOn(AndroidSchedulers.mainThread())
  136.         // .subscribe(bitmap -> myImageView.setImageBitmap(bitmap));
  137.  
  138.         // subscribeOn(Scheduler scheduler): Asynchronously subscribes Observers
  139.         // to this Observable on the specified Scheduler.
  140.  
  141.         // observeOn(Scheduler scheduler): Modifies an Observable to perform its
  142.         // emissions and notifications on a specified Scheduler, asynchronously
  143.         // with a bounded buffer.
  144.  
  145.         // check: http://reactivex.io/documentation/operators/subscribeon.html
  146.  
  147.     }
  148.  
  149.     private static String getError(String name) {
  150.         throw new RuntimeException();
  151.     }
  152.  
  153.     // OUTPUT:
  154.     // 1. Hello, world!
  155.     // 1. the end
  156.     // 2. Hello, world!-Krzysztof
  157.     // 3. Hello, world!-Krzysztof
  158.     // 4. -1028118321
  159.     // 5. -1538652498
  160.     // 6. -1846029788
  161.     // 7. Name: Krzysztof
  162.     // 7. Name: Karol
  163.     // 7. Name: Irek
  164.     // 8. Krzysztof is awesome- this is the result
  165.     // 9. lalalla
  166.     // 9. Krzysztof is awesome- this is the result
  167.     // 10. error - this is the result
  168.  
  169. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement