Using RxJava 2 - Tutorial - Vogel
Using RxJava 2 - Tutorial - Vogel
(http://www.vogella.com)
http://www.vogella.com/tutorials/RxJava/article.html 1/32
7/9/2018 Using RxJava 2 - Tutorial
2.1. Observables
Observables are the sources for the data. Usually they start
providing data once a subscriber starts listening. An observable
may emit any number of items (including zero items). It can
terminate either successfully or with an error. Sources may never
terminate, for example, an observable for a button click can
potentially produce an infinite stream of events.
2.2. Subscribers
A observable can have any number of subscribers. If a new item is
emitted from the observable, the onNext() method is called on
each subscriber. If the observable finishes its data flow successful,
the onComplete() method is called on each subscriber. Similar, if
the observable finishes its data flow with an error, the onError()
method is called on each subscriber.
3. RxJava example
A very simple example written as JUnit4 test is the following:
http://www.vogella.com/tutorials/RxJava/article.html 2/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
package com.vogella.android.rxjava.simple;
import org.junit.Test;
Online Traini
import io.reactivex.Observable; (https://learn.vogel
GROOVY
compile group: 'io.reactivex.rxjava2', name: 'rxjava', version:
'2.1.1'
For Maven, you can add RxJava via the following snippet.
http://www.vogella.com/tutorials/RxJava/article.html 3/32
7/9/2018 Using RxJava 2 - Tutorial
XML
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
<version>2.0.4</version> Online Traini
</dependency> (https://learn.vogel
Type Description
http://www.vogella.com/tutorials/RxJava/article.html 4/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
Observable<Todo> todoObservable = Observable.create(new
ObservableOnSubscribe<Todo>() {
@Override
public void subscribe(ObservableEmitter<Todo> Online Traini
emitter) throws Exception { (https://learn.vogel
try {
List<Todo> todos =
RxJavaUnitTest.this.getTodos(); QUICK LINKS
for (Todo todo : todos) { 15 OCT - RC
emitter.onNext(todo);
Training
}
(http://www.vo
emitter.onComplete();
} catch (Exception e) { vogella Traini
emitter.onError(e); (http://www.vo
} vogella Books
}
(http://www.vo
});
SHARE
Using lambdas, the same statement can be expressed as:
JAVA
Observable<Todo> todoObservable = Observable.create(emitter ->
{
try {
List<Todo> todos = getTodos();
for (Todo todo : todos) {
emitter.onNext(todo);
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
});
JAVA
Maybe<List<Todo>> todoMaybe = Maybe.create(emitter -> {
try {
List<Todo> todos = getTodos();
if(todos != null && !todos.isEmpty()) {
emitter.onSuccess(todos); 1
} else {
emitter.onComplete(); 2
}
} catch (Exception e) {
emitter.onError(e); 3
}
});
3 An error occurred
http://www.vogella.com/tutorials/RxJava/article.html 5/32
7/9/2018 Using RxJava 2 - Tutorial
Observable.fromIterable() - takes an
java.lang.Iterable<T> and emits their values in their order
in the data structure
Online Traini
Observable.fromArray() - takes an array and emits their (https://learn.vogel
values in their order in the data structure
QUICK LINKS
Observable.fromCallable() - Allows to create an observable
15 OCT - RC
for a java.util.concurrent.Callable<V> Training
Observable.fromFuture() - Allows to create an observable for (http://www.vo
vogella Traini
a java.util.concurrent.Future
(http://www.vo
Observable.interval() - An observable that emits Long vogella Books
objects in a given interval (http://www.vo
Similar methods exists for the other data types, e.g., SHARE
* Flowable.just() , Maybe.just() and Single.just .
JAVA
Observable<Todo> todoObservable = Observable.create(emitter ->
{ ... });
JAVA
DisposableObserver<Todo> disposableObserver =
todoObservable.subscribeWith(new DisposableObserver<Todo>() {
@Override
public void onNext(Todo t) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
http://www.vogella.com/tutorials/RxJava/article.html 6/32
7/9/2018 Using RxJava 2 - Tutorial
@Override
public void onSuccess(List<Todo> todos) {
// work with the resulting todos
}
@Override
public void onError(Throwable e) {
// handle the error case
}
});
http://www.vogella.com/tutorials/RxJava/article.html 7/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.disposables.CompositeDisposable; Online Traini
(https://learn.vogel
CompositeDisposable compositeDisposable = new
CompositeDisposable();
QUICK LINKS
Single<List<Todo>> todosSingle = getTodos(); 15 OCT - RC
Training
Single<Happiness> happiness = getHappiness();
(http://www.vo
@Override
public void onError(Throwable e) {
// handle the error case
}
}));
compositeDisposable.add(happiness.subscribeWith(new
DisposableSingleObserver<Happiness>() {
@Override
public void onSuccess(Happiness happiness) {
// celebrate the happiness :-D
}
@Override
public void onError(Throwable e) {
System.err.println("Don't worry, be happy! :-P");
}
}));
The following code does the expensive web query 4 times, even
though doing this once would be fine, since the same Todo objects
should be shown, but only in different ways.
http://www.vogella.com/tutorials/RxJava/article.html 8/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
Single<List<Todo>> todosSingle = Single.create(emitter -> {
Thread thread = new Thread(() -> {
try {
List<Todo> todosFromWeb = // query a webservice Online Traini
(https://learn.vogel
System.out.println("Called 4 times!");
showTodosInATable(todosSingle); SHARE
anotherMethodThatsSupposedToSubscribeTheSameSingle(todosSingle)
;
The next code snippet makes use of the cache method, so that the
Single instance keeps its result, once it was successful for the first
time.
JAVA
Single<List<Todo>> todosSingle = Single.create(emitter -> {
Thread thread = new Thread(() -> {
try {
List<Todo> todosFromWeb = // query a webservice
emitter.onSuccess(todosFromWeb);
} catch (Exception e) {
emitter.onError(e);
}
});
thread.start();
});
showTodosInATable(cachedSingle);
anotherMethodThatsSupposedToSubscribeTheSameSingle(cachedSingle
);
http://www.vogella.com/tutorials/RxJava/article.html 9/32
7/9/2018 Using RxJava 2 - Tutorial
Online Traini
Flowab toObser reduce() scan() ignoreEl (https://learn.vogel
le vable() element element ements()
At() At() QUICK LINKS
firstEle first()/fi 15 OCT - RC
ment() rstOrErr Training
lastEle or() (http://www.vo
http://www.vogella.com/tutorials/RxJava/article.html 10/32
7/9/2018 Using RxJava 2 - Tutorial
Online Traini
Comple toFlowa toObser toMayb toSingle (https://learn.vogel
table ble() vable() e() ()
toSingle QUICK LINKS
Default( 15 OCT - RC
) Training
(http://www.vo
vogella Traini
7. RxAndroid (http://www.vo
vogella Books
7.1. Using RxAndroid (http://www.vo
GRADLE
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.8'
For example you can define a long running operation via the
following observable.
JAVA
final Observable<Integer> serverDownloadObservable =
Observable.create(emitter -> {
SystemClock.sleep(1000); // simulate delay
emitter.onNext(5);
emitter.onComplete();
});
You can now subscribe to this observable. This triggers its execution
and provide the subscribe with the required information.
JAVA
serverDownloadObservable.
observeOn(AndroidSchedulers.mainThread()). 1
subscribeOn(Schedulers.io()). 2
subscribe(integer -> {
updateTheUserInterface(integer); //
this methods updates the ui
view.setEnabled(true); // enables
it again
});
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
http://www.vogella.com/tutorials/RxJava/article.html 11/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
@Override
protected void onDestroy() {
super.onDestroy();
if (bookSubscription != null &&
!bookSubscription.isDisposed()) {
bookSubscription.dispose();
}
}
http://www.vogella.com/tutorials/RxJava/article.html 12/32
7/9/2018 Using RxJava 2 - Tutorial
GROOVY
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.8'
compile 'com.squareup.okhttp:okhttp:2.5.0' Online Traini
testCompile 'junit:junit:4.12' (https://learn.vogel
Also enable the usage of Java 8 in your app/build.gradle file. QUICK LINKS
15 OCT - RC
GROOVY Training
android {
(http://www.vo
// more stuff
compileOptions { vogella Traini
sourceCompatibility JavaVersion.VERSION_1_8 (http://www.vo
targetCompatibility JavaVersion.VERSION_1_8 vogella Books
}
(http://www.vo
}
SHARE
8.2. Create activities
Change your main layout file to the following.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/first"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="First"
/>
<Button
android:id="@+id/second"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Second"
/>
<Button
android:id="@+id/third"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Third"
/>
</LinearLayout>
RxJavaSimpleActivity
BooksActivity
ColorsActivity
http://www.vogella.com/tutorials/RxJava/article.html 13/32
7/9/2018 Using RxJava 2 - Tutorial
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout Online Traini
(https://learn.vogel
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" QUICK LINKS
>
15 OCT - RC
<Button Training
android:id="@+id/button" (http://www.vo
android:layout_width="wrap_content" vogella Traini
android:layout_height="wrap_content"
(http://www.vo
android:text="Server"
/> vogella Books
<Button (http://www.vo
android:id="@+id/toastbutton"
android:layout_width="wrap_content" SHARE
android:layout_height="wrap_content"
android:text="Toast"
android:onClick="onClick"
/>
<TextView
android:id="@+id/resultView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result"
/>
</LinearLayout>
activity_colors.xml
http://www.vogella.com/tutorials/RxJava/article.html 14/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
package com.vogella.android.rxjava.simple;
import android.os.Bundle;
import android.os.SystemClock; Online Traini
import android.support.v7.app.AppCompatActivity; (https://learn.vogel
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView; QUICK LINKS
import android.widget.Toast; 15 OCT - RC
Training
import io.reactivex.Observable;
(http://www.vo
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; vogella Traini
import io.reactivex.disposables.Disposable; (http://www.vo
import io.reactivex.schedulers.Schedulers; vogella Books
(http://www.vo
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rxjavasimple);
View view = findViewById(R.id.button);
view.setOnClickListener(v -> {
v.setEnabled(false); // disables the button until
execution has finished
Disposable subscribe = serverDownloadObservable.
observeOn(AndroidSchedulers.mainThread()).
subscribeOn(Schedulers.io()).
subscribe(integer -> {
updateTheUserInterface(integer); //
this methods updates the ui
v.setEnabled(true); // enables it again
});
disposable.add(subscribe);
});
}
@Override
protected void onStop() {
super.onStop();
if (disposable!=null && !disposable.isDisposed()) {
disposable.dispose();
}
}
http://www.vogella.com/tutorials/RxJava/article.html 15/32
7/9/2018 Using RxJava 2 - Tutorial
}
}
QUICK LINKS
15 OCT - RC
Training
(http://www.vo
vogella Traini
(http://www.vo
vogella Books
(http://www.vo
SHARE
http://www.vogella.com/tutorials/RxJava/article.html 16/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
package com.vogella.android.rxjava.simple;
import android.content.Context;
import android.support.v7.widget.RecyclerView; Online Traini
import android.view.LayoutInflater; (https://learn.vogel
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; QUICK LINKS
import android.widget.Toast; 15 OCT - RC
Training
import java.util.ArrayList;
(http://www.vo
import java.util.List;
vogella Traini
/** (http://www.vo
* Adapter used to map a String to a text view. vogella Books
*/
(http://www.vo
public class SimpleStringAdapter extends
RecyclerView.Adapter<SimpleStringAdapter.ViewHolder> {
SHARE
private final Context mContext;
private final List<String> mStrings = new ArrayList<>();
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.strin
g_list_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, final int
position) {
holder.colorTextView.setText(mStrings.get(position));
holder.itemView.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext,
mStrings.get(position), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return mStrings.size();
}
http://www.vogella.com/tutorials/RxJava/article.html 17/32
7/9/2018 Using RxJava 2 - Tutorial
}
}
}
Online Traini
Implement ColorsActivity which uses a observable to receive a (https://learn.vogel
list of colors.
QUICK LINKS
Create the activity_colors.xml layout file. 15 OCT - RC
Training
XML (http://www.vo
<?xml version="1.0" encoding="utf-8"?>
vogella Traini
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android" (http://www.vo
android:layout_width="match_parent" vogella Books
android:layout_height="match_parent" (http://www.vo
>
<android.support.v7.widget.RecyclerView
android:id="@+id/color_list"
SHARE
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
http://www.vogella.com/tutorials/RxJava/article.html 18/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
package com.vogella.android.rxjava.simple;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity; Online Traini
import android.support.v7.widget.LinearLayoutManager; (https://learn.vogel
import android.support.v7.widget.RecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configureLayout();
createObservable();
}
@Override
protected void onStop() {
super.onStop();
if (disposable!=null && !disposable.isDisposed()) {
disposable.dispose();
}
}
}
http://www.vogella.com/tutorials/RxJava/article.html 19/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
package com.vogella.android.rxjava.simple;
import android.content.Context;
import android.os.SystemClock; Online Traini
(https://learn.vogel
import java.util.ArrayList;
import java.util.List;
QUICK LINKS
/** 15 OCT - RC
* This is a fake REST client.
Training
*
(http://www.vo
* It simulates making blocking calls to an REST endpoint.
*/ vogella Traini
public class RestClient { (http://www.vo
private Context mContext; vogella Books
(http://www.vo
public RestClient(Context context) {
mContext = context;
} SHARE
http://www.vogella.com/tutorials/RxJava/article.html 20/32
7/9/2018 Using RxJava 2 - Tutorial
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" Online Traini
android:layout_height="match_parent" (https://learn.vogel
>
</FrameLayout>
http://www.vogella.com/tutorials/RxJava/article.html 21/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
package com.vogella.android.rxjava.simple;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity; Online Traini
import android.support.v7.widget.LinearLayoutManager; (https://learn.vogel
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar; QUICK LINKS
15 OCT - RC
import java.util.List;
Training
(http://www.vo
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers; vogella Traini
import io.reactivex.disposables.Disposable; (http://www.vo
import io.reactivex.schedulers.Schedulers; vogella Books
(http://www.vo
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
restClient = new RestClient(this);
configureLayout();
createObservable();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (bookSubscription != null &&
!bookSubscription.isDisposed()) {
bookSubscription.dispose();
}
}
http://www.vogella.com/tutorials/RxJava/article.html 22/32
7/9/2018 Using RxJava 2 - Tutorial
@Override
protected void onStop() {
super.onStop();
if (bookSubscription!=null &&
!bookSubscription.isDisposed()) { Online Traini
bookSubscription.dispose(); (https://learn.vogel
}
}
QUICK LINKS
}
15 OCT - RC
Training
8.3. Implement a long running implementation (http://www.vo
The long running operation will run in the background, the update
of the UI will happen in the main thread.
http://www.vogella.com/tutorials/RxJava/article.html 23/32
7/9/2018 Using RxJava 2 - Tutorial
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" Online Traini
android:layout_height="match_parent" (https://learn.vogel
>
<TextView
android:id="@+id/messagearea" SHARE
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:text=""
android:layout_below="@+id/scheduleLongRunningOperation"
/>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_alignBottom="@+id/scheduleLongRunningOperation"
android:layout_toEndOf="@+id/scheduleLongRunningOperation"
/>
</RelativeLayout>
http://www.vogella.com/tutorials/RxJava/article.html 24/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
package com.vogella.android.rxjava.simple;
import android.os.Bundle;
import android.os.SystemClock; Online Traini
import android.support.v7.app.AppCompatActivity; (https://learn.vogel
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView; QUICK LINKS
15 OCT - RC
import java.util.concurrent.Callable;
Training
(http://www.vo
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers; vogella Traini
import io.reactivex.disposables.Disposable; (http://www.vo
import io.reactivex.observers.DisposableObserver; vogella Books
import io.reactivex.schedulers.Schedulers;
(http://www.vo
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configureLayout();
createObservable();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (subscription != null && !subscription.isDisposed())
{
subscription.dispose();
}
}
subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainTh
read()).
doOnSubscribe(disposable ->
{
progressBar.setVisibility(View.VISIBLE);
button.setEnabled(false);
http://www.vogella.com/tutorials/RxJava/article.html 25/32
7/9/2018 Using RxJava 2 - Tutorial
messagearea.setText(messagearea.getText().toString() +"\n"
+"Progressbar set visible" );
}
). Online Traini
subscribe(getDisposableObserver()); (https://learn.vogel
}
});
QUICK LINKS
}
15 OCT - RC
Callable<String> callable = new Callable<String>() { Training
@Override (http://www.vo
public String call() throws Exception {
vogella Traini
return doSomethingLong();
} (http://www.vo
}; vogella Books
(http://www.vo
public String doSomethingLong(){
SystemClock.sleep(1000);
SHARE
return "Hello";
}
/**
* Observer
* Handles the stream of data:
*/
private DisposableObserver<String> getDisposableObserver()
{
return new DisposableObserver<String>() {
@Override
public void onComplete() {
messagearea.setText(messagearea.getText().toString() +"\n"
+"OnComplete" );
progressBar.setVisibility(View.INVISIBLE);
button.setEnabled(true);
messagearea.setText(messagearea.getText().toString() +"\n"
+"Hidding Progressbar" );
}
@Override
public void onError(Throwable e) {
messagearea.setText(messagearea.getText().toString() +"\n"
+"OnError" );
progressBar.setVisibility(View.INVISIBLE);
button.setEnabled(true);
messagearea.setText(messagearea.getText().toString() +"\n"
+"Hidding Progressbar" );
}
@Override
public void onNext(String message) {
messagearea.setText(messagearea.getText().toString() +"\n"
+"onNext " + message );
}
};
}
}
JAVA
@Test QUICK LINKS
public void
15 OCT - RC
anObservableStreamOfEventsAndDataShouldEmitsEachItemInOrder() {
Training
Observable<String> pipelineOfData = (http://www.vo
Observable.just("Foo", "Bar"); vogella Traini
(http://www.vo
pipelineOfData.subscribe(testObserver);
vogella Books
List<Object> dataEmitted = testObserver.values(); (http://www.vo
assertThat(dataEmitted).hasSize(2);
assertThat(dataEmitted).containsOnlyOnce("Foo"); SHARE
assertThat(dataEmitted).containsOnlyOnce("Bar");
}
All base reactive types now have a test() method. This is a huge
convenience for returning TestSubscriber or TestObserver.
JAVA
TestSubscriber<Integer> ts = Flowable.range(1, 5).test();
http://www.vogella.com/tutorials/RxJava/article.html 27/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
package com.vogella.android.rxjava.simple;
import org.junit.Test;
Online Traini
import java.util.List; (https://learn.vogel
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter; QUICK LINKS
import io.reactivex.ObservableOnSubscribe; 15 OCT - RC
import io.reactivex.observers.TestObserver;
Training
(http://www.vo
import static junit.framework.Assert.assertTrue;
vogella Traini
(http://www.vo
public class RxJavaUnitTest { vogella Books
String result="";
(http://www.vo
@Test
public void expectNPE(){
Observable<Todo> todoObservable = Observable.create(new
ObservableOnSubscribe<Todo>() {
@Override
public void subscribe(ObservableEmitter<Todo>
emitter) throws Exception {
try {
List<Todo> todos =
RxJavaUnitTest.this.getTodos();
if (todos == null){
throw new NullPointerException("todos
was null");
}
for (Todo todo : todos) {
emitter.onNext(todo);
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
}
});
TestObserver<Object> testObserver = new TestObserver<>
();
todoObservable.subscribeWith(testObserver);
http://www.vogella.com/tutorials/RxJava/article.html 28/32
7/9/2018 Using RxJava 2 - Tutorial
Online Traini
(https://learn.vogel
QUICK LINKS
15 OCT - RC
Training
(http://www.vo
vogella Traini
(http://www.vo
vogella Books
(http://www.vo
SHARE
http://www.vogella.com/tutorials/RxJava/article.html 29/32
7/9/2018 Using RxJava 2 - Tutorial
JAVA
package com.vogella.android.rxjava.simple;
import org.junit.Test;
Online Traini
import java.util.List; (https://learn.vogel
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter; QUICK LINKS
import io.reactivex.ObservableOnSubscribe; 15 OCT - RC
import io.reactivex.observers.TestObserver;
Training
(http://www.vo
import static junit.framework.Assert.assertTrue;
vogella Traini
(http://www.vo
public class RxJavaUnitTest { vogella Books
String result="";
(http://www.vo
@Test
public void expectNPE(){
Observable<Todo> todoObservable = Observable.create(new
ObservableOnSubscribe<Todo>() {
@Override
public void subscribe(ObservableEmitter<Todo>
emitter) throws Exception {
try {
List<Todo> todos =
RxJavaUnitTest.this.getTodos();
if (todos == null){
throw new NullPointerException("todos
was null");
}
for (Todo todo : todos) {
emitter.onNext(todo);
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
}
});
TestObserver<Object> testObserver = new TestObserver<>
();
todoObservable.subscribeWith(testObserver);
http://www.vogella.com/tutorials/RxJava/article.html 30/32
7/9/2018 Using RxJava 2 - Tutorial
Online Traini
11. About this website
(https://learn.vogel
QUICK LINKS
Support free Questions and Tutorial & code Get the source code
content discussion license 15 OCT - RC
Training
(http://www.vo
(http://www.vogella.com/code/index.html)
(http://www.vogella.com/support.html)
(http://www.vogella.com/contact.html)
(http://www.vogella.com/license.html) vogella Traini
(https://github.com/ReactiveX/RxJava/wiki/What’s-different-in-2.0)
SHARE
Rx Java with Android Examples from Kaushik Gopal
(https://github.com/kaushikgopal/RxJava-Android-Samples)
http://www.vogella.com/tutorials/RxJava/article.html 31/32
7/9/2018 Using RxJava 2 - Tutorial
Version 1.1
Last updated 2018-02-13 12:00:43 +01:00
http://www.vogella.com/tutorials/RxJava/article.html 32/32