RxJava is out there for quite sometime and people are hearing about its greater capabilities, but lot of them haven’t started yet. If you are one of them, you are late to party, but that’s ok; better late than never. Few developers I spoke with says there is no proper guide available (we can find lot of good articles spread across multiple websites than in a single place) or they fear starting something new.

In this series, I am aiming to write series of tutorials covering basics to advanced topics in RxJava and RxAndroid.

I am hoping this article series make any novice developer, an RxAndroid developer in weeks time.

We’ll start with basic theoretical explanation of few terms you come across in reactive programming and later get on to few code examples.

1. What is Reactive Programming

Reactive Programming is basically event-based asynchronous programming. Everything you see is an asynchronous data stream, which can be observed and an action will be taken place when it emits values. You can create data stream out of anything; variable changes, click events, http calls, data storage, errors and what not. When it says asynchronous, that means every code module runs on its own thread thus executing multiple code blocks simultaneously.

An advantage of asynchronous approach is, as every task runs on its own thread, all the task can start simultaneously and amount of time takes complete all the tasks is equivalent to the longer task in the list. When it comes to mobile apps, as the tasks runs on background thread, you can achieve seamless user experience without blocking main thread.

  • A simple example (from Wikipedia) can be x = y + z; where the sum of y and z is assigned to x. In reactive programming, when the y value changes, the value of x will be updated automatically without re-executing the x = y + z statement. This can be achieved by observing the value of y or z.
  • An array list can be a data steam and an action can be taken when each item it emitted. May be you want to filter out the even numbers and ignoring the odd numbers. This can be done using usual loops and conditional statements, but in reactive programming you can achieve this in a completely different approach.

When you start your app in Reactive Programming, the way you design your architecture and the way you write code changes completely. It’s even becomes more powerful when met with Clean Architecture, MVP, MVVM and other design patters.

2. Reactive Extensions

Reactive Extensions (ReactiveX or RX) is a library that follows Reactive Programming principles i.e compose asynchronous and event based programs by using observable sequence. These libraries provides set of interfaces and methods which helps developers write clean and simpler code.

Reactive Extensions are available in multiple languages C++ (RxCpp), C# (Rx.NET), Java (RxJava), Kotlin (RxKotlin), Swift (RxSwift) and lot more. We specifically interested in RxJava and RxAndroid as android is our focused area.

3. What is RxJava

RxJava is Java implementation of Reactive Extension (from Netflix). Basically it’s a library that composes asynchronous events by following Observer Pattern. You can create asynchronous data stream on any thread, transform the data and consumed it by an Observer on any thread. The library offers wide range of amazing operators like map, combine, merge, filter and lot more that can be applied onto data stream.

You will understand more about operators and transformations when you start working on actual code examples.

4. What is RxAndroid

RxAndroid is specific to Android Platform with few added classes on top of RxJava. More specifically, Schedulers are introduced in RxAndroid (AndroidSchedulers.mainThread()) which plays major role in supporting multithreading concept in android applications. Schedulers basically decides the thread on which a particular code runs whether on background thread or main thread. Apart from it everything we use is from RxJava library only.

Even through there are lot of Schedulers available, Schedulers.io() and AndroidSchedulers.mainThread() are extensively used in android programming. Below are the list of schedulers available and their brief introduction.

  • Schedulers.io() – This is used to perform non CPU-intensive operations like making network calls, reading disc / files, database operations etc., This maintains pool of threads.
  • AndroidSchedulers.mainThread() – This provides access to android Main Thread / UI Thread. Usually operations like updating UI, user interactions happens on this thread. We shouldn’t perform any intensive operations on this thread as it makes the app glitchy or ANR dialog can be thrown.
  • Schedulers.newThread() – Using this, a new thread will be created each time a task is scheduled. It’s usually suggested not to use schedular unless there is a very long running operation. The threads created via newThread() won’t be reused.
  • Schedulers.computation() – This schedular can be used to perform CPU-intensive operations like processing huge data, bitmap processing etc., The number of threads created using this scheduler completely depends on number CPU cores available.
  • Schedulers.single() – This scheduler will execute all the tasks in sequential order they are added. This can be used when there is necessity of sequential execution is required.
  • Schedulers.immediate() – This scheduler executes the the task immediately in synchronous way by blocking the main thread.
  • Schedulers.trampoline() – It executes the tasks in First In – First Out manner. All the scheduled tasks will be executed one by one by limiting the number of background threads to one.
  • Schedulers.from() – This allows us to create a scheduler from an executor by limiting number of threads to be created. When thread pool is occupied, tasks will be queued.

Now we have the basic concepts needed. Let’s start with some key concepts of RxJava that everyone should aware of.

4. RxJava Basics: Observable, Observer

RxJava is all about two key components: Observable and Observer. In addition to these, there are other things like Schedulers, Operators and Subscription.

Observable: Observable is a data stream that do some work and emits data.

Observer: Observer is the counter part of Observable. It receives the data emitted by Observable.

Subscription: The bonding between Observable and Observer is called as Subscription. There can be multiple Observers subscribed to a single Observable.

Operator / Transformation: Operators modifies the data emitted by Observable before an observer receives them.

Schedulers: Schedulers decides the thread on which Observable should emit the data and on which Observer should receives the data i.e background thread, main thread etc.,

5. RxJava Basic Examples

Now we have good theoretical knowledge about Reactive Programming, RxJava and RxAndroid. Let’s jump on to some code examples to understand the concepts better.

Adding Dependencies

To get started, you need to add the RxJava and RxAndroid dependencies to your projects build.gradle and sync the project.

// RxJava
implementation 'io.reactivex.rxjava2:rxjava:2.1.9'

// RxAndroid
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'

The Basic Steps

1. Create an Observable that emits data. Below we have created an Observable that emits list of animal names. Here just() operator is used to emit few animal names.

Observable<String> animalsObservable = Observable.just("Ant", "Bee", "Cat", "Dog", "Fox");

2. Create an Observer that listen to Observable. Observer provides the below interface methods to know the the state of Observable.

  • onSubscribe(): Method will be called when an Observer subscribes to Observable.
  • onNext(): This method will be called when Observable starts emitting the data.
  • onError(): In case of any error, onError() method will be called.
  • onComplete(): When an Observable completes the emission of all the items, onComplete() will be called.

Observer<String> animalsObserver = getAnimalsObserver();

private Observer<String> getAnimalsObserver() {
        return new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.d(TAG, "onSubscribe");
            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "Name: " + s);
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "All items are emitted!");
            }
        };
    }

3. Make Observer subscribe to Observable so that it can start receiving the data. Here, you can notice two more methods, observeOn() and subscribeOn().

  • subscribeOn(Schedulers.io()): This tell the Observable to run the task on a background thread.
  • observeOn(AndroidSchedulers.mainThread()): This tells the Observer to receive the data on android UI thread so that you can take any UI related actions.
animalsObservable
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(animalsObserver);

If you run the program, you can see the below output in your LogCat.

onSubscribe
Name: Ant
Name: Bee
Name: Cat
Name: Dog
Name: Fox
All items are emitted!

That’s all, you just wrote your first RxJava program. We are going to learn more about Schedulers and Observers in subsequent articles. But for now this information is sufficient to get started.

Example 1: Basic Observable, Observer

Here is complete code of the above example. Run the activity and check the output in LogCat.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;


import info.androidhive.rxandroidexamples.R;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class Example1Activity extends AppCompatActivity {

    /**
     * Basic Observable, Observer, Subscriber example
     * Observable emits list of animal names
     */

    private static final String TAG = Example1Activity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example1);

        // observable
        Observable<String> animalsObservable = getAnimalsObservable();

        // observer
        Observer<String> animalsObserver = getAnimalsObserver();

        // observer subscribing to observable
        animalsObservable
                .observeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(animalsObserver);
    }

    private Observer<String> getAnimalsObserver() {
        return new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.d(TAG, "onSubscribe");
            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "Name: " + s);
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "All items are emitted!");
            }
        };
    }

    private Observable<String> getAnimalsObservable() {
        return Observable.just("Ant", "Bee", "Cat", "Dog", "Fox");
    }
}
Output:
onSubscribe
Name: Ant
Name: Bee
Name: Cat
Name: Dog
Name: Fox
All items are emitted!

Example 2: Introducing Disposable

In this example we gonna introduce new component called Disposable.

  • Disposable: Disposable is used to dispose the subscription when an Observer no longer wants to listen to Observable. In android disposable are very useful in avoiding memory leaks.

    Let’s say you are making a long running network call and updating the UI. By the time network call completes its work, if the activity / fragment is already destroyed, as the Observer subscription is still alive, it tries to update already destroyed activity. In this case it can throw a memory leak. So using the Disposables, the un-subscription can be when the activity is destroyed.

In the below example you can see a Disposable is used and calling disposable.dispose() in onDestroy() will un-subscribe the Observer.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import info.androidhive.rxandroidexamples.R;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class Example2Activity extends AppCompatActivity {

    /**
     * Basic Observable, Observer, Subscriber example
     * Observable emits list of animal names
     * You can see Disposable introduced in this example
     */
    private static final String TAG = Example2Activity.class.getSimpleName();

    private Disposable disposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example2);

        // observable
        Observable<String> animalsObservable = getAnimalsObservable();

        // observer
        Observer<String> animalsObserver = getAnimalsObserver();

        // observer subscribing to observable
        animalsObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(animalsObserver);
    }

    private Observer<String> getAnimalsObserver() {
        return new Observer<String>() {

            @Override
            public void onSubscribe(Disposable d) {
                Log.d(TAG, "onSubscribe");
                disposable = d;
            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "Name: " + s);
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "All items are emitted!");
            }
        };
    }

    private Observable<String> getAnimalsObservable() {
        return Observable.just("Ant", "Bee", "Cat", "Dog", "Fox");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // don't send events once the activity is destroyed
        disposable.dispose();
    }
}

This will generate the same output as earlier example.

Example 3: Introducing Operator

Now we’ll see another example by introducing an operator to transform the emitted data. In the below example filter() operator is used to filter out the emitted data.

  • filter() operator filters the data by applying a conditional statement. The data which meets the condition will be emitted and the remaining will be ignored.

In the below example the animal names which starts with letter `b` will be filtered.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import info.androidhive.rxandroidexamples.R;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

public class Example3Activity extends AppCompatActivity {

    /**
     * Basic Observable, Observer, Subscriber example
     * Observable emits list of animal names
     * You can see Disposable introduced in this example
     */
    private static final String TAG = Example3Activity.class.getSimpleName();

    private Disposable disposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example3);

        // observable
        Observable<String> animalsObservable = getAnimalsObservable();

        // observer
        Observer<String> animalsObserver = getAnimalsObserver();

        // observer subscribing to observable
        animalsObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<String>() {
                    @Override
                    public boolean test(String s) throws Exception {
                        return s.toLowerCase().startsWith("b");
                    }
                })
                .subscribeWith(animalsObserver);
    }

    private Observer<String> getAnimalsObserver() {
        return new Observer<String>() {

            @Override
            public void onSubscribe(Disposable d) {
                Log.d(TAG, "onSubscribe");
                disposable = d;
            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "Name: " + s);
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "All items are emitted!");
            }
        };
    }

    private Observable<String> getAnimalsObservable() {
        return Observable.fromArray(
                "Ant", "Ape",
                "Bat", "Bee", "Bear", "Butterfly",
                "Cat", "Crab", "Cod",
                "Dog", "Dove",
                "Fox", "Frog");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // don't send events once the activity is destroyed
        disposable.dispose();
    }
}

If you run the example, you can see the animal names that starts with letter `b` printed in LogCat.

Output:
onSubscribe
Name: Bat
Name: Bee
Name: Bear
Name: Butterfly
All items are emitted!

Example 4: Multiple Observers and CompositeDisposable

Consider a case where you have multiple Observables and Observers. Disposing them in Destroy one bye one is a tedious task and it can be error prone as you might forgot to dispose. In this case we can use CompositeDisposable.

  • CompositeDisposable: Can maintain list of subscriptions in a pool and can dispose them all at once.
    Usually we call compositeDisposable.clear() in onDestroy() method, but you can call anywhere in the code.

In the below example, you can notice two observers animalsObserver and animalsObserverAllCaps subscribed to same Observable. The both observers receives the same data but the data changes as different operators are applied on the stream.

  • animalsObserver: – The filter() operator is used to filter the animal names starting with letter `b`.
  • animalsObserverAllCaps: – The filter() operator is used to filter the animal names starting with letter `c`. Later map() operator is used to convert each animal name to all capital letters. Using multiple operators on a single observer is called chaining of operators.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import info.androidhive.rxandroidexamples.R;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class Example4Activity extends AppCompatActivity {

    /**
     * Basic Observable, Observer, Subscriber example
     * Observable emits list of animal names
     * You can see filter() operator is used to filter out the
     * animal names that starts with letter `b`
     */
    private static final String TAG = Example4Activity.class.getSimpleName();

    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example4);

        Observable<String> animalsObservable = getAnimalsObservable();

        DisposableObserver<String> animalsObserver = getAnimalsObserver();

        DisposableObserver<String> animalsObserverAllCaps = getAnimalsAllCapsObserver();

        /**
         * filter() is used to filter out the animal names starting with `b`
         * */
        compositeDisposable.add(
                animalsObservable
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .filter(new Predicate<String>() {
                            @Override
                            public boolean test(String s) throws Exception {
                                return s.toLowerCase().startsWith("b");
                            }
                        })
                        .subscribeWith(animalsObserver));

        /**
         * filter() is used to filter out the animal names starting with 'c'
         * map() is used to transform all the characters to UPPER case
         * */

        compositeDisposable.add(
                animalsObservable
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .filter(new Predicate<String>() {
                            @Override
                            public boolean test(String s) throws Exception {
                                return s.toLowerCase().startsWith("c");
                            }
                        })
                        .map(new Function<String, String>() {
                            @Override
                            public String apply(String s) throws Exception {
                                return s.toUpperCase();
                            }
                        })
                        .subscribeWith(animalsObserverAllCaps));
    }

    private DisposableObserver<String> getAnimalsObserver() {
        return new DisposableObserver<String>() {

            @Override
            public void onNext(String s) {
                Log.d(TAG, "Name: " + s);
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "All items are emitted!");
            }
        };
    }

    private DisposableObserver<String> getAnimalsAllCapsObserver() {
        return new DisposableObserver<String>() {


            @Override
            public void onNext(String s) {
                Log.d(TAG, "Name: " + s);
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "All items are emitted!");
            }
        };
    }

    private Observable<String> getAnimalsObservable() {
        return Observable.fromArray(
                "Ant", "Ape",
                "Bat", "Bee", "Bear", "Butterfly",
                "Cat", "Crab", "Cod",
                "Dog", "Dove",
                "Fox", "Frog");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // don't send events once the activity is destroyed
        compositeDisposable.clear();
    }
}

If you run this example, you can see the below output. Here the animal names that starts with `B` are observed by animalsObserver. All the names starting with letter `c` and in all capital letters are observed by animalsObserverAllCaps.

Output:
Name: Bat
Name: Bee
Name: Bear
Name: Butterfly
All items are emitted!
Name: CAT
Name: CRAB
Name: COD
All items are emitted!

Example 5: Custom Data Type, Operators

Finally we’ll conclude this article with an interesting example. In this, instead of using just primitive data types, we are going to use a custom data type i.e Note model. We use same Observable and Observer concept here except the streamed data is of Note data type.

  • Here map() operator is used to convert all the notes to all uppercase format.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import info.androidhive.rxandroidexamples.R;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class Example4Activity extends AppCompatActivity {


    /**
     * Basic Observable, Observer, Subscriber example
     * Introduced CompositeDisposable and DisposableObserver
     * The observable emits custom data type (Note) instead of primitive data types
     * ----
     * .map() operator is used to turn the note into all uppercase letters
     * ----
     * You can also notice we got rid of the below declarations
     * Observable<Note> notesObservable = getNotesObservable();
     * DisposableObserver<Note> notesObserver = getNotesObserver();
     */
    private static final String TAG = Example4Activity.class.getSimpleName();

    private CompositeDisposable disposable = new CompositeDisposable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example4);

        // add to Composite observable
        // .map() operator is used to turn the note into all uppercase letters
        disposable.add(getNotesObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<Note, Note>() {
                    @Override
                    public Note apply(Note note) throws Exception {
                        // Making the note to all uppercase
                        note.setNote(note.getNote().toUpperCase());
                        return note;
                    }
                })
                .subscribeWith(getNotesObserver()));
    }

    private DisposableObserver<Note> getNotesObserver() {
        return new DisposableObserver<Note>() {

            @Override
            public void onNext(Note note) {
                Log.d(TAG, "Note: " + note.getNote());
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "All notes are emitted!");
            }
        };
    }

    private Observable<Note> getNotesObservable() {
        final List<Note> notes = prepareNotes();

        return Observable.create(new ObservableOnSubscribe<Note>() {
            @Override
            public void subscribe(ObservableEmitter<Note> emitter) throws Exception {
                for (Note note : notes) {
                    if (!emitter.isDisposed()) {
                        emitter.onNext(note);
                    }
                }

                if (!emitter.isDisposed()) {
                    emitter.onComplete();
                }
            }
        });
    }

    private List<Note> prepareNotes() {
        List<Note> notes = new ArrayList<>();
        notes.add(new Note(1, "buy tooth paste!"));
        notes.add(new Note(2, "call brother!"));
        notes.add(new Note(3, "watch narcos tonight!"));
        notes.add(new Note(4, "pay power bill!"));

        return notes;
    }

    class Note {
        int id;
        String note;

        public Note(int id, String note) {
            this.id = id;
            this.note = note;
        }

        public int getId() {
            return id;
        }

        public String getNote() {
            return note;
        }

        public void setId(int id) {
            this.id = id;
        }

        public void setNote(String note) {
            this.note = note;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposable.clear();
    }
}
Output:
Id: 1, note: BUY TOOTH PASTE!
Id: 2, note: CALL BROTHER!
Id: 3, note: WATCH NARCOS TONIGHT!
Id: 4, note: PAY POWER BILL!
All notes are emitted!

That’s all for now. I hope this article gave you good introduction about RxJava.

Further Reading

I have prepared complete beginner course listing down the necessary articles required to further improvise your knowledge in RxJava. I am assuming the course requires any where between 2-3 weeks of your time to turn you from a novice developer to moderate RxJava developer.

Checkout the RxJava Complete Beginner Course

Please do comment if you have any queries or suggestions.
Happy Coding πŸ™‚

Author

  • kk

    nice….easy to understnd with the help of digrams….!!!

  • Grsandhya

    superb easy to learn thanks

  • Thanh Trung

    Thanks. This tutorial is very usefull!
    Hope you have many tutorials like this.

  • Hobby 110

    Nice tutorial…

  • Gudeamit148

    awesome man

  • Nm15

    Great work explaining this. Im taking an online Android class, and you covered this theme with far more clarity than the class im paying for.
    Again thanks

  • Edie

    U R awsome … Great job and amazing work

  • Amaaaaaaaaazing !

  • Madhu54108

    Splendid work
    Explanation with images is the very good way..
    Thank you

  • Raouabenfredj

    This tutorial is very clear, but when I put in a TableRow: 4 textview in the same colum colum and who is near him I just want to put 4 EditView. known me how I can achieve it.pleeeeeease :)))

    • try to place a EditText after textview and see how it comes.

      • abbasi.android

        hi ,
        i want to solve an expression , by using calculator in android
        i just want to click the required numbers and operators
        and want to solve the expression , in text view
        hw could i?

  • Dung Nguyen

    thanks, but where is “4. Grid View, 5. Tab Layout, 6. List View”? More please

    • I already wrote them. Please go through pagination of this blog.

  • Ramiz Mohamed

    Does not come any better than this. Much appreciated.

  • Ramiz Mohamed

    Very comprehensive but simple enough to understand. Well done.

  • Mahesh Anil Thokala

    [I18N] Hardcoded string “Email:”, should use @string resource.
    i got these warnings how i can remove.please help me.

    • Yes this warning is in new Android OS. You shouldn’t hard a string in XML instead you need to store the value in strings.xml and use that name here

      Like When creating new project in default main.xml, there will be hello string (project title).

      • Mahesh Anil Thokala

        I got another warning “This text field does not specify an inputType or a hint” But output comes in emulator,thaaaanks alot,you helped me alot……….

  • Luis Alberto Baigorria Rodas

    Hi. Ravi Tamada! Do you have any example multi-touch with a image in Android. I need it! Please! Congratulations for Androidhive! Very Good examples! Regards from Santa Cruz, Bolivia!

  • Thank man! Help me a lot

  • Hey Ravi Tamada

    What program you use to design picture

    i want to use design my layout icon

    Thank you ^^

  • Ravi Tamada

    i have problem

    i want to create custom Layout

    LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayoutTest);
    setContentView(ll);

    but error

    you can help me?

    thank you ^^

  • Manas

    Really it is a demo that marked as superb. I am salute the author for a great job.
    pls. keep it up

  • Yakub

    Excellent….

  • Sameertm

    sooooooooooperb

  • jitendra

    Great posted tutorial ..excellent ……………….

  • Thanks man..Great tutorials

  • Mokamoddo

    This is just perfect. Thanks RAVI. You’re the man.

  • Gandi Gangadhar

    xmlns means xml namespace…….., what is the use of it

  • Tuan

    Thank Ravi so much

  • Bad2Guy

    thank for beginner

  • Mahalakshmi

    super

  • Sur

    Best Android Tutorial site ever

  • Thanks a ton for your article, everything is clearly explained

  • yungyung

    Thank you for working

  • Funjabiwala

    u r the boss… i am really fan of this site..thanks a lot

  • 516613535

    the TableRow’s child TextView’s android:layout_width is match_parent,why it doesn’t fill up with its parent??

  • Siva Brahma

    It is very nice simply superb.

  • Vijjumailto

    thank u so much good article.

  • sumit garg

    i want to know how to set Layouts using only java coding not by xml file.

  • Please how can bring all this table to start from the bottom up.

  • kartheek

    mind blowing, awesome, easy way to learn

  • Harish Thakur

    good

  • Mitulgoti001

    very good sir ji

  • Viswa

    Excellent !!

  • Steve

    It has helped me a lot.

    Thanks a lot

  • Deekshit

    Its really amazing article. Thanks for making the article as simple to understand. πŸ™‚

  • rehaman

    thanks a lot ravi….i getting easy

    • tieudongta

      thank u very much

  • I am surprised to see GridView and ListView as listed in types of Layouts.

    And
    1. GridLayout is also available from API 14.
    2. what about FrameLayout which is there since API level 1?

  • Pavithakavin

    explanations are too good.very useful for me.
    thank u so much

  • Bappahgarga

    sir, what are the different between linear layout and table layout?

  • deepu

    Thanks a lot…it was neat and clear demo…fantanstic

  • Softsnmm

    thanks, I think…. I will be succ

  • Shaikhjuberk

    really dude u r superub it really helps a lot………thank you.

  • Jyoti Maimt

    thnkss…..itsss help me lot………….

  • Akkinenisurekha

    hey ravi could u tell me differences about relative & table

  • Chokoste

    thanks very helpful

  • S Kumar2958

    Hi Sir,

    Your blogs is very nice and most helpful for us. I request to you please upload more about android and if you have such PDF ebook , Please mail me . My mail Id is s.kumar2958@gmail.com. I will wait your response , Please help me.

    • Suresh

      alert(“Web Site Hacked”);

      • Jarod

        wow! How did U do that?!!!! πŸ™‚ Haker pierwszej wody

    • suhail

      hello

      please if you got some PDF or ebook please foreword it to me on suhail.ryadi@gmail.com

      regards

  • gunjan verma

    Good Post…………….. keep it up……………

  • gunjan verma

    Good Post…………….. keep it up……

  • praki

    thanx……..

  • Zealtolearn

    Really its informative..thanks for describing with example.

  • Prashant Hirapara

    I wanted to clear this confusion about different layouts and this just did that…loved it…thanks !!

  • Can Uludağ

    That is a great explanation

  • Raiyani sagar

    thanks…

  • Durga

    Blog is more useful,,,,need more updates

  • Maya Saif

    great job thanks

  • Quanghits

    Great tutorial.

  • go open source

    AMAZING TUTORIAL …. I LIKE IT..

  • Caracola

    Great explanation. Thanks!

  • pavan deshpande

    Pavan

    @ (http://www.pavanhd.blogspot.in/)

    You May Also Like this
    android linear layout

  • Roneykakkanatt
  • thanks so much

  • Dharam

    Great Demo. its Awsome!

  • vishal

    thannx

  • Faraz Ahmad

    Very helpful….

  • GIang

    What is the function of shrinkColumns?

  • Fiyas

    Learn ANDROID from ANDROIDITUTS

    http://www.androidituts.com

  • Umesh

    You are simply superb

  • vadd

    TnankU!

  • smart@sunil

    as a beginner its good

  • Abhimanyu

    nice yr……..

  • Ravikumar

    Wow ! i got it in one shot …………………. thnx

  • Chu Myat Moe

    very clear explaining. Easy to realize and give useful knowledge. Thz a lot. πŸ™‚

  • Dariush

    tnx πŸ™‚

  • Murali

    it’s nice article to beginers…thanks

  • Meghna

    Thanks man.. Nice examples.. Even this
    http://www.compiletimeerror.com/2013/06/android-linearlayout-example.html might help, have a look…

  • KAlyan

    awesome dude!!

  • Harshal Voonna

    How do i have a progress bar on top of my imageview

  • why google hasn’t mentioned about the table layout here…http://developer.android.com/guide/topics/ui/declaring-layout.html

  • Akbar

    GREAT JOB! Thanks for these awesome articles.

  • Rohan Rana

    reallyy…thanku veryy muchhh

  • aldson diego

    Thanks. This tutorial is very good!

  • Akshay

    Thanks alot for the post it is very clear and easy to understand!!

  • Ashish Kumar Singh

    good explanation.. πŸ™‚
    thanks..

  • bhavesh

    very nice demo

  • yourkishore

    You really dont know how much this helped me thanks alot, i know you from 9lessons also, i thing you are brother of srinivas tamada, Appreciate your both works.

  • James

    I don’t normally bother replying to these kind of things but I wanted to compliment your clear explanation of these features. I am currently going through all of your tutorials even though I have a few years of experience in other areas (php/mysql/c#/asp/jquery/css/flash) and I think your tutorials are excellently explained. Thanks a lot for contributing to the internet in a positive way!

  • Muskaan Sharam

    fantastic tutorial.. the way, you explained is very easy and much more understandable.. Thanks

  • Nusrat

    Nice Introduction πŸ™‚

  • Abdul Wahab

    Easy and Informative

  • Muhammad hussain

    How you can design this sketch layout. I want to do this for my project work. Help me please to do my wireframe alike. Thank

  • nikhil

    thanks super easy !

  • Arun

    Really Superb..!!

  • ben

    I love u…really!!!!
    Was searchin for this kinda explanation. Noone could explain except u…:*

  • gopi

    U R GREAT

  • Sandun Abeywickrama

    Thank u !!!

  • Yusuf Yak

    Wonderful…this one of the best android tutorial site in the WORLD!!!!!!!!!

  • The Power of Love

    Thank you! This really helped me figure out how I could achieve what I wanted to do.

  • Thank you Ravi πŸ™‚

  • A way from Away

    Thank you its very helpful

  • gonza28

    Thanks for your tutorials and resources. Congratulations

  • Thanks for the article, but you should really get rid of all your “fill_parent” strings and replace them with “match_parent”. Both of these do the same thing and so including both in the same source file like you did just adds to confusion. “fill_parent” has been deprecated in favour of “match_parent” since API level 8 and in fact both resolve to the same constant, -1.

  • dinesh

    i am very beginner in android. im really impressed with ur tutorials..good job

  • vikas balyan

    great job..

  • fiqkyrahman

    good job

  • AMBIKA

    Good Man

  • mohid

    Well done.. πŸ™‚

  • RN

    What tool do you use to draw these mock-up?

  • sujeethkumar

    Really superb nice tutorial……

  • Why not take a look at my blog about how to create an Android app that displays an Image in an ImageView control of the main Activity at the full width of the screen.

    The app uses the following Android SDK objects:

    . ImageView
    . LinearLayout
    . Bitmap
    . Activity
    . XML layout
    . LayoutParams
    . Display

    Also:
    . layout_width
    . layout_height
    . orientation
    . id
    . vertical
    . match_parent

    XML attributes and values are covered.

    Click the link BELOW! to see

    http://androidprogrammeringcorner.blogspot.com/2015/06/pak-longs-android-programming-corner.html

  • Why not take a look at my blog about how to create an Android app that displays an Image in an ImageView control of the main Activity at the full width of the screen.

    The app uses the following Android SDK objects:

    . ImageView
    . Bitmap
    . LinearLayout
    . Activity
    . XML layout
    . LayoutParams
    . Display

    Also:
    . layout_width
    . layout_height
    . orientation
    . id
    . vertical
    . match_parent

    XML attributes and values are covered.

    Click the link BELOW! to see

    http://androidprogrammeringcorner.blogspot.com/2015/06/pak-longs-android-programming-corner.html

  • If you would like to learn how to use the following objects to write an Android application that displays a vertically upward scrolling Rainbow of colours in a FREE video, then click the link at the end of this comment:

    . LinearLayout
    . Activity
    . View
    . Canvas
    . ArrayList
    . Paint

    http://androidprogrammeringcorner.blogspot.com/2015/06/pak-longs-android-programming-corner_24.html

  • Shabana Parveen

    nice explanation. thanks πŸ™‚

  • Vishvam

    Excellent work. Amazing great…

  • SHAUN

    Awesome work Ravi… Yes its true being an experienced developer even i couldnt figure out any tutorial that would help people to understand the reason why we use Rxjava….
    Really amazing tutorial to understand what is Reactive programming and why it is used

    • Thanks Shaun. Please read the other articles too and make yourself good at RxJava.

      All the best!

  • Deep Dave

    You totally nailed it bhaai.
    I was wandering around for somewhere to begin.
    Wonderful.
    Thank you very much πŸ™‚

  • Vicky Rana

    Very Simple Explaination Ravi ji, awesome tutorials about Rx java and Rx android

    • Thanks Vicky. Complete all the articles to understand Rx well.

      • Vicky Rana

        Thank You ravi ji

  • Sabit Ahmad

    Very good tutorial On RX java

  • Sri Kanth P

    Thanks a lot. Very Good Tutorial.
    Eagerly waiting for “Dagger 2” and “Android Architecture Components” !!!

  • siddik

    Very simplest tutorial. Last few months i have very struggle to start the rx java. Now i got the basic knowledge. Thanks ravi.

    • Cheers! Pls explore other articles too πŸ™‚

  • Truong Pham

    Thank a lot Very Good Tutorial , when call Observable animalsObservable = Observable.just(“Ant”, “Bee”, “Cat”, “Dog”, “Fox”); have a error Can’t resolve method just , I have add library , Help me Ravi Tamada

    • Check the import statement of Observable. It might be wrong.

      • Truong Pham

        Yes sir , I resolved it when add io.reactivex.Observable.just(“Cricket”, “Football” ,”Brother”,”inch”);

  • Sandeep Dhiman

    Nice Tutorial available so far ..Does RxJava provide its on method for making a post or get request or we have to use retrofit or any other library?

  • Yup have seen this too.

  • Sai Babu

    Today I understood what is RxJava actually is…thank you Ravi for such nice examples..very much informative..

  • Abdulmajid Abdulhamid

    Thanks Dear Ravi

  • Younes Charfaoui

    really thank you, finally i understood what is RXjava , it was some kind of mystery to me πŸ˜€ ,thank you

  • Reyansh Mishra

    Hey Ravi Love you blog. There is s typo CPI-Intensive, search it (ctr+f).

    • Thanks for pointing it out. Corrected it:)

  • Rahul R

    Hi Ravi Thanks for simple and crispy tutorial for the reactive java and reactive android.

  • MaggicBones

    Ravi Tamada You are AMAZING, Thank You!

  • Trey Rosius

    Very Comprehensive…Thanks for sharing

  • awinash kumar

    Thank you Ravi for excellent tutorial to RxJava. I am facing many time related to RxJava interview question but not give proper answer. But now i am to explain them.

  • awinash kumar

    Ravi you have any planning to Start dependency injection such as Dagger2 ?

  • karthick Ramanathan

    Ravi, you are amazing, 1000 hats off

  • TimeTraveler

    Thanks a lot Ravi, for such a amazing tutorial, i am following your post from years, you are such an amazing guy who explain each block of code beautifully. i don’t know how i missed this post which is hot and important topic right now.. if you let me know any subscription where i can subscribe to your channel so that will get any latest post updates through mail..Thanks a lot..

    • Hello

      Thanks for being a long time follower:) I don’t have a subscription module separately, but you can login at http://download.androidhive.info/ to get subscribed.

      Have a nice day!

      • TimeTraveler

        Ok Ravi, Thanks..

  • Rahul Kumar

    Hi Ravi,

    Thanks a lot for this wonderful article. Please write a blog on android design pattern like MVC, MVP etc. Thanks again.

  • Yasir Ali

    Hi Ravi! Can u please tell me why we use RXJAVA for network call…please give me a solid concept..
    and can we achieve realtime data like Firebase using our sql server or android rxjava ?

  • Sumit Raj

    Just a small feedback, please have published date for the articles so that the viewers get the correct context when you say 2 years back.

    • Hi Sumit

      I got your point. I have removed the date for the purpose of the SEO. Google is decreasing the ranking or users are not reading the articles if the content is old. I’ll modify the line ‘2 years back’.

      Thanks for your suggestion.

  • Mayur Musrif

    Concise example ! Keep up the good work ! Thank you for a wonderful example !

  • yathavan yogarajah

    hi i know java basic level, i am developing android using java i have a confusion about what i must learn next (kotlin or RxJava or java deep). i wold like to work foreign companies so please suggest the right way

    • Hi

      The three are different. Learn Java well. Then RxJava. Kotlin is a different language targeting JVM. Writing apps in Kotlin is much easier as it provides lot of boilerplate code.

      I suggest learn all of them πŸ™‚

      • yathavan yogarajah

        Thanks Ravi

  • I heard about Rx-Java around 2 years ago but I have been reluctant to use it due to the inadequate and clattered resources about it. But with these articles everything is different and I feel confident enough to use Rx-java on my next projects.

    • Thanks Kelvin.

      Happy learning πŸ™‚

    • Patriotic Nigerian

      Exactly same issue i was having onboarding.

  • Dhruv Rastogi

    Hii Ravi,

    Thanks for making such a good tutorials, Are you planning to start tutorials for react-native in near future?

    • Currently no Dhruv. Not getting much to main the mail site itself πŸ™

  • Shahbaz Ahmed

    Nice Article πŸ™‚

  • Ahmad Dudayef

    Thank u ravi, really clear and easy understanding

  • abbas aniefa

    Good one to understand the basics of Rx.

  • shikto shishir

    Wonderful article.!

  • Neeraj Singh

    Superb Good Job…

  • Ram Bhawan Kushwaha

    Hi Ravi!
    Wonderful article. ! very helpful for me and other to basic understating for RX Java .

  • mini

    Can you please review your outputs as they refer different inputs. Please see Example for filter

    • Which example you are referring to? There are multiple examples with filter operator.

  • Patriotic Nigerian

    This is awesome!!!! Other tutorials i saw were complicated. So now i am gonna read all your tutorials on RxJava and RxAndroid. https://uploads.disquscdn.com/images/b56557939784b56cec20c6a53d35ed42936276571bd92521199254c7a141514c.jpg

    • All the best πŸ™‚

    • Sonal Agrawal

      I just started to learn RxJava and tried to run your first example, but it’s showing compile time error at two lines.
      error: cannot find symbol method observeOn(Scheduler)
      error: cannot find symbol method just(String,String,String,String,String)

  • Kuanysh Les

    Amazing tutorial!!! I’ll recommend all of people who intent to learn about RxJava – start with this article!!

  • ankita saini

    Hiiii….Thanks for the explanation.
    can you please tell me ,what is the difference between DisposableObserver and Observer..?

    • DisposableObserver is something you can dispose once the usage is over or the activity is killed. Usually you need to dispose the Observer before the activity is destroyed so that you can avoid memory leaks. When you have only one Observer, you can use DisposableObserver and dispose it. If you have multiple Observers, you can create normal Observers and dispose all of them at once using CompositeDisposable.

      • ankita saini

        Thank you πŸ™‚

  • Ashwani Kumar

    I cannot see any difference between these two schedulers:

    Schedulers.single() – This scheduler will execute all the tasks in sequential order they are added. This can be used when there is necessity of sequential execution is required.

    Schedulers.trampoline() – It executes the tasks in First In – First Out manner. All the scheduled tasks will be executed one by one by limiting the number of background threads to one.

    Can you please elaborate on these two.

    Thanks

  • kalidoss rajendran

    Awesome tutorial!!!!…Very useful

  • Htoo Aung Hlaing

    Hi, Ravi, Example3Activty will be print out only Bee,
    not print like this,
    “onSubscribe
    Name: Bat
    Name: Bee
    Name: Bear
    Name: Butterfly
    All items are emitted!”
    cuz , you didn’t declare, Bat, Bear & Butterfly, plz recheck the code πŸ˜€

  • Ashik Azeez

    Thankas a lot,i have seen some video tutorials about this, but this article more much better that tutorials.πŸ‘πŸ‘

  • Rahul Sontakke

    Nice blog & it’s good to start with RxJava & RxAndroid!!

  • Vasim

    This is excellent explanation about RxJava, I would like to know can you make a article along with a example by using as Retrofit,RxJava and Dagger ?

  • Pranoy Dutta

    Thanks for making it so clear & simple!

  • Inderjit Singh

    great tutorial with explanation.

  • Sai Kiran

    Where to intialize the progress dialog and dismiss the progress dialog..

    • You can use doOnSubscribe and doOnTerminate to show / hide the progress dialog.

  • Chandrakant K

    Thanks you saved my job bro…. πŸ™‚

  • anup pathak

    Very well explained !!!

  • Irfan Irawan Sukirman

    Good job @ravi8x:disqus. thanks for your great explanation

  • Mohak Gupta

    Wonderful Article πŸ™‚

  • Yup. Will correct it.

    Thank you

  • Pranav Lathigara

    Hi Ravi can you explain me when we have to use this

    return Observable.create(new ObservableOnSubscribe() {
    @Override
    public void subscribe(ObservableEmitter emitter) throws Exception {

    }
    });

    BTW great Explanation

  • venkat

    Hi Ravi, i’m following your post from 1 and half year onwards and i learned a lot from your blocks. If you done any RxSwift tutorial can you share the link.

  • Jaykrushna Solanki

    Thank you very much Ravi Sir. I have feel fear to learn Reactive Programming because of confusing articles on web. after read your article and write your example code. debug flow of the code. now i get some confidence to learn Reactive Programming

  • Martin Gelevski

    Ravi thanks for the tutorial, this helped me a lot with RxJava understanding.

  • Nice tutorial!

  • Jaimin

    Hello Ravi, This tutorial is awesome. Please add explanation about methods just(), fromArray() and .create() and .subscribe().

  • Kaleem Patel

    Thanks for this tutorial, Easy to understand explanation and demonstration.This is the best article I have read about RXAndroid till date.

  • Vα»‹t

    Thank you so much

  • Brandon Chapman

    There is a minor bug here. To get the output in example 5 you need to use:
    ” Log.d(TAG, “Id: ” + note.getId() + “, note: ” + note.getNote());”

  • AMAL SHIWANTHA

    A very good tutorial. Any example with retrofit rxjava dagger 2
    Thank you RAVI

  • George Radu

    @ravi8x:disqus thank you for this great introductory course! Very clear and helpful! You are awesome!

    George,
    Romania

  • Faakhy

    Thank you very much πŸ™‚

  • mohamed elagamy

    Great Tutorial

  • Vishal Prakash

    Awesome tutorial @ravi8x:disqus Thanks!, It is very helpful.

  • pradeepkumar reddy

    can we replace android loaders using RX Java ? If yes, how ? can you explain with an example ?

  • Muhammad Xoshnaw

    Thank you that was useful πŸ™‚

  • Harshita

    @ravi8x:disqus , subscribeOn method showing “Cannot resolve method subscribeOn” error with DisposableObserver. Why is this happening, can you please explain. Why subscribeOn not working with DisposableObserver

    • Harshita

      Yes it’s working, sorry for this comment

  • Shubhransu Nandi

    hi Ravi.. I have a doubt. BY using this Rx concept , if we are making any network call using retrofit . Suppose we will get the data in the UI . At our activity is visible , if something changes in the response(added any values in server) then is that result automatically reflect to the UI ? or do we need to make another call for our new data ?
    Please rectify me if i am wrong ……._

  • Kevin Moses Kenap

    Hello bro, what is the different between Observer and DisposableObserver class? thx

    • Hi Kevin

      Both do the same job. The observal has to be disposed / disconnected on activity killed. So in Android, we use DisposableObserver to do that.

  • rajesh

    Can not resolve method just(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String)

    • sayar samanta

      try to do with fromArray();

  • Sagar Ghare

    thanks ravi sir. That is very clear tutorial.

  • alejandro vazquez

    I had already read about Android Reactive Programming in some others tutorials, but this one has been the one which has made me love this programming paradigm. It vas very clear and easy to understand. Thank you very much Ravi for the tutorial . I am looking forward learning more about reactive programming. I loved it

    Regards from Mexico

  • Kuanysh Les

    Amazing tutorial!!

  • janak heer

    good explanation brother

  • vamsi sangaraju

    Bro u will do videos on this Bro

  • Zulfi

    This is Awesome man!

  • Adit Chauhan

    Such a great way explanation, have been following you from last 5 years.
    You never disappointed. people android hunt ends here only .
    Great. thanks for sharing your knowledge from so m
    any years.

    • Hi Adit

      Thanks for being a long time follower. I am glad the blog helped you πŸ™‚

      • Adit Chauhan

        yes it did, right from my college days, when I created feed app. you have been very responsive to your fb messages.
        Thanks for putting effort for developers like us. fan of your ethics.

  • Abbasali

    Hello Ravi,
    Thanks a lot for the simple explanation
    I don’t understand one thing why cannot we use composite disposable with subscribe().you have used subscribewith()

  • Manisha Kamble

    Amazing tut , always helping for learning new things in android. i always started learning with your code.

  • Harshvardhan Singh Gaharwar

    in which situation mostly we hav to use rxjava any live examples of real time

  • @Ravi Tamada. Thank a lots your the tutorial help me clean RxJava & RxAndroid understanding.