Saturday, April 20, 2024
HomeAndroidRxAndroid Example - RxAndroid Tutorial #2

RxAndroid Example – RxAndroid Tutorial #2

-

In this RxAndroid Example Tutorial, we will continue our previous topic on RxAndroid tutorial‘s Getting started where we discussed about the basics of RxJava 2 and RxAndroid and its uses.

Now, we are going to integrate the RxAndroid in our Project and write a simple Android Project which shows how to declare an Observable, Observer and subscribe to the Observable to receive the data.

rxandroid example tutorial logo

In this tutorial, we will be creating a simple android project where upon whenever we make a simple button click we would be making our observable emit some data and at the same time our observer subscribes and emits data which we can see via toast messages. So let’s get started.

This article is part of RxJava Intro series. You can checkout the entire series here:

Below image demonstrates what we would be targeting at the end of the RxAndroid Example Project:

RxAndroid Example Project final output demo gif

The complete code for this tutorial is given at the bottom of the article.

Methods which we will be using in this RxAndroid Example tutorial:

create()Creates a new Observable. This method is available from Observable class

onNext(T value) – Emits a value. This method is from Emitter interface.

onComplete() – called upon completion of Emission of data. This method is also from Emitter interface.

3 Simple Steps to demonstrate RxAndroid Example:

1. Creating an Observable

Lets begin by creating the Observable which will emit the data when user clicks a button. Here I am using Observable’s create() method.

    mObservable = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                for(int i=1; i<=5;i++){
                    e.onNext(i);
                }
                e.onComplete();
            }
        });

As we know that now Android Studio 3 supports Java 8 features, let us use Lambda expressions which we discussed in our Previous Tutorial on Android Java 8 Features Integration.

Now the above code can be reduced to the following using Lambda Expressions:

mObservable = Observable.create(e -> {
            for(int i=1; i<=5;i++){
                e.onNext(i);
            }
            e.onComplete();
        });

2. Creating an Observer

Let us create an Observer and overriding all the required methods such as onSubscribe, onNext, onError, onComplete.

  mObserver = new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {
                Toast.makeText(MainActivity.this, "onSubscribe called", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(Integer integer) {
                Toast.makeText(MainActivity.this, "onNext called: " + integer, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(MainActivity.this, "onError called", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {
                Toast.makeText(MainActivity.this, "onComplete called", Toast.LENGTH_SHORT).show();
            }
        };

3. Subscribing Observer to Observable

This subscription can be done in a simple one liner:

mObservable.subscribe(mObserver);

Our completed RxAndroid Example Activity:

Now the finished MainActivity.java will look as follows:


package com.coderefer.rxandroidexamples.intro;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.coderefer.rxandroidexamples.R;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
public class SimpleRxAndroidActivity extends AppCompatActivity {
private Observable<Integer> mObservable;
private Observer<Integer> mObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// code to initialize Observable
private void initializeObservable() {
mObservable = Observable.create(e -> {
for(int i=1; i<=5;i++){
e.onNext(i);
}
e.onComplete();
});
}
// Code to initialize Observer
private void initializeObserver() {
mObserver = new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
Toast.makeText(SimpleRxAndroidActivity.this, "onSubscribe called", Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(Integer integer) {
Toast.makeText(SimpleRxAndroidActivity.this, "onNext called: " + integer, Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Throwable e) {
Toast.makeText(SimpleRxAndroidActivity.this, "onError called", Toast.LENGTH_SHORT).show();
}
@Override
public void onComplete() {
Toast.makeText(SimpleRxAndroidActivity.this, "onComplete called", Toast.LENGTH_SHORT).show();
}
};
}
// method which will be called on button click
public void performAction(View view) {
initializeObservable();
initializeObserver();
// subscribing observer to observable
mObservable.subscribe(mObserver);
}
}

Now we can see that whenever our button is clicked, Our Observable emits data and Observer subscribes and receives data.

The Complete code for this tutorial can be downloaded here:

[emaillocker]

rxandroid example tutorial link

[/emaillocker]

In the next tutorial of RxAndroid, we will see different ways to create Observables and much more!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

LATEST POSTS

SOLID Principles in Android with Kotlin Examples

Recently I had an interview experience where I went blank when the interviewer posed an Interesting Question - Explain SOLID Principles and how they are...

Building a Multi Module App in Android | Modularization in Android #1

Recently, I was in requirement for developing a Multi Module app in Android and I was going through this great lecture on it. This article...

Lambda function in Kotlin with Examples

Lambda function is powerful feature in any Programming language and Lambda function in Kotlin is no exception. In this article, we will look at how...

Higher Order Functions in Kotlin with examples

There are many advanced features in Kotlin which gives an edge for the user using this language over Java. One such feature is Higher Order...

Follow us

1,358FansLike
10FollowersFollow
401SubscribersSubscribe

Most Popular