Skip to content

📎 This app demonstrates how to use RxJava for asynchronous operations in Android app

Notifications You must be signed in to change notification settings

eun-jegal/SampleApp-RxJava

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RxJava Sample App

This sample app demonstrates the modern Android architecture pattern - MVVM(Model, View, ViewModel) using RxJava and Retrofit. The app provides detail information about movies fetched from the server.



Tech Stack

  • Minumum SDK Level: 21
  • 100% Kotlin
  • MVVM Pattern: Industry-recognized software architecure pattern supported by Google
  • ViewModel: Exposes data streams as a state holder
  • Lifecycle: Observes Android lifecycles and handle operations to a change in the lifecycle status
  • RxJava: Java VM implementation of Reactive Extensions: a library for composing asynchronous and event-based programs by using observable sequences
  • RxAndroid: Reactive extenstions for Android
  • Retrofit: Type-safe REST client for Android, Java and Kotlin developed by Square.
  • OkHttp : 3rd party library sending and receive HTTP-based network requests built on top of the Okio library
  • GSON: Java library that can be used to convert Java Objects into their JSON representation

RxJava

RxJava is a Java VM implementation of ReactiveX a library for composing asynchronous and event-based programs by using observable sequences.

Relationship between Observable and Observer

"Observable" and "Observer" are two key components of RxJava. We need to understand how data streams work within RxJava.

  • Oberservable: Observable is a speaker which broadcasts the data value.
  • Operator: Operator converts or modifies the data emitted from Observable before Observer receives the data.
  • Observer: Observer is a subscriber of Observer. It receives the data emitted from Observable.
  • Subscription: A relationship between Observable and and a single Observer. There can be multiple Observers subscribed to a single Observable.

Schedulers

Schedulers is responsible for managing which thread to execute tasks related to the operation of an Observable chain. There are two main Schedulers widely used in Android platfrom.

  • Schedulers.io(): This is used to perform non-CPU-intensive operations like making network calls, reading disc/files, database operations, etc., This maintains a pool of threads
  • AndroidSchedulers.mainThread() This provides us access to the main thread of the application to perform actions like updating the UI. We shouldn’t perform any intensive operations on this thread as ANR dialog can be thrown.

How to subscribe to Observable

fun getAllMovies() {
    val response = repository.getAllMovies()
    response.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(observer)
}
  • When we call getAllMovies(), repository returns a response as "Observable" object from API call
  • subscribeOn(Schedulers.io()): Tells Observable to run the task(fetching data from the server) on a background thread.
  • observeOn(AndroidSchedulers.mainThread()): Tells the Observer to receive the data on the main UI thread so that you can update the screen.
  • subscribe(): Takes Observer as a parameter which receives the data emitted by Observable.

How to handle a subscription

Observer needs to take a proper action(update the screen) after receiving data emitted from Observable. Observer object needs to implement following interfaces to handle the result of data received from Observable.

private val observer: Observer = object : Observer {
        override fun onSubscribe(d: Disposable) {
            disposable = d
        }
    override fun onNext(t: Movies) {
        _movieList.postValue(t)
    }

    override fun onError(e: Throwable) {
        _movieList.postValue(null)
    }

    override fun onComplete() {
    }

}

  • onSubscribe(): Called when Observer subscribes to Observable. It contains a Disposable instance as parameter whose Disposable.dispose() can be called anytime to cancel the connection or dispose the subscription when an Observer no longer wants to listen to Observable. In Android, disposable are very useful in avoiding memory leaks.
  • onNext(): Called when Observable starts emitting the data.
  • onError(): Called if any error occurs.
  • onComplete(): Called when Observable completes the emission of all the items.

App Architecture

This sample was built with Google's recommended modern app architecture - MVVM pattern. By separating multiple app components into two layers - UI and Data, the app is scalable, maintainable and testable.

  • Architectural Principles
    • Separations of concerns
    • Drive UI from data models
    • Single source of truth
    • Unidirectional Data Flow

UI Layer

UI layer displays the application data and serves as the primary point for user interactions. Whenever the app data changes, the UI should update to reflect changes made by either user interaction or external input.

  • The main activity has a fragment container view and two fragments are replaced following user interactions. Main fragment displays a list of movies fetched from the server. When the user selects one of the movies, detailed information is displayed in the detail fragment.
  • MainViewModel holds state and plays as a bridge between UI elements and the data layer
  • UI elements request actions to ViewModel and observer ViewModel's livedatas to automatically update screens

Data Layer

Data layer is reponsible for containing application data and business logics. The data layer is consisted of repositories and data sources. It is important to keep each repository as a single source of truth.

  • Repository is a single source of truth and requests data to APIService which fetches data from the network server.
  • APIService gets data from the server using Retrofit library.

References

The purpose of this project was to understand how to use RxJava to operate asynchronous operations in Android apps. You can check out more information about RxJava in following links.

  • Types of Observables in RxJava
  • Android App using RxJava, Rerofit with MVVM Architecture
  • About

    📎 This app demonstrates how to use RxJava for asynchronous operations in Android app

    Topics

    Resources

    Stars

    Watchers

    Forks

    Languages