Functional Reactive Programming:Functions and Rx coupled Together


Functional programming with Rx Java

Hi dear readers,I am back with something new that is Functional programming in coupling with Rx Java.Before we start,I'd like to give brief introduction about Functional Programming which is introduced in java 8 with Lambda Expressions(( ) =>,seems familiar?).





Functional Programming is based on functional paradigm,it is simply used for computational tasks.Functional programming follows mathematical approach using Lambda expressions.With this approach,functions are passed as arguments to other functions.Before we dive deep into functional programming and lambda expressions.I'd like to start with a one line(quick to grasp) definition for all.Here,we go:

Lambda Expressions

Lambda expressions are the first step on the way to functional programming.One should have complete understanding of lambda expressions before starting with functional programming.


Basic syntax of Lambda expression is as follows:

parameter -> expression body

<p>(arg1, arg2...) -> { body }</p>


<p>(type1 arg1, type2 arg2...) -> { body }</p>

Lambda expressions is like anonymous function,like anonymous classes it doesn't have declarations.It is a method without access specifier,return type.It is somewhat like inline functions in c/c++.Lambda expressions is a shorthand of a function.It is mainly useful in cases where a method needs to be called once and have small definition.Example of lambda expressions is:


(int a, int b) -> {  return a + b; }

Lambda expressions are used primarily to define inline implementation of a functional interface.
Functional Interfaces/SAM(Single Abstract Method) interfaces are those interfaces in java which has only abstract method in them.Functional interfaces can take generic parameter type.For customized functional interface we need to create an interface with one abstract method and should be annotated with @FunctionalInterface. An example for functional interface is as follows:


// in java.lang package
interface Runnable { void run(); }

Few more things about lambda expressions:
  • They can take zero or more parameters.
  • Body of lambda expressions can contain zero or more statements.
  • Explicit type declaration can be done or type can be inferred form context.
After lambda expressions,we need to start with Functional programming.


Functional Programming

Functional programming is introduced in Java 8.It is basically based on functional paradigm,as clear from its name its key point are functions.This approach works on focusing on computation tasks rather than performing actions.Objects in Functional paradigm are immutable(unchangeable) i.e.they are either const or final.Pure functions are building blocks in Functional Programming.
A pure function is a function which guarantees that for a given input it will produce the same output for same set of input parameters ,no matter how many times it is called.Example of pure functions is like strlen(),sqrt().

Simple Example of  Functional Programming
 
Runnable r1 = () -> {
   System.out.println("My Runnable");
  };

In case of SAM,we can omit curly braces also.Then above statement can be written as:

Runnable r1 = (s) -> System.out.println(s);

Functional Reactive Programming

Functional reactive programming (FRP) is a term which is combination of functional programming with Rx java.Rx java is an extension to JVM's reactive extensions.Rx java is a library for composing asynchronous and event-based programs by using observable sequences.RxJava is a port from Netflix of the Reactive Extensions (Rx) to Java. RxJava was open sourced 2014 and is hosted at http://reactivex.io/. The Java version of this concept is called RxJava and is hosted under https://github.com/ReactiveX/RxJava. RxJava is published under the Apache 2.0 license.Rx java supports java 6 or higher.



FRP works on Observer pattern,which means Data is omitted as stream which is observed by an Observer. Observables are stream from which data flows.
The Observer Pattern involves two roles: a source Observable, and one or many Observers that are interested in the events or objects that the source Observable will be emitting. The Observable emits objects, while the Observer "subscribes" and receives them. 

Basic terms to start with Rx java are:

1.Observable and Subscriber

Observables are the pipelines which emit data,events and Subscriber are the watchman to consume data being emitted from the Observables. An observable emits data only when there is subscription to it.i.e There should be a subscriber to it.A subscriber has three methods in it which are onNext(),onCompleted() and onError().




When a well defined observable emits data all these three methods will be called in respective conditions like if an error is encountered in between of data transmission onError().
Basic example :

Observable<String> observable= Observable.just("Lets Start")

Subscriber class implements the Observer interface and provides some additional useful methods other than default ones.Some of them are:
  • onStart() , a method which is invoked when the Subscriber has been a subscriber to the Observable and before the Observable has emitted any data.
  • isUnsubscribed(), a method that indicates whether this Subscriber has unsubscribed from the list of subscriptions.
  • unsubscribe(), a method that stops the receipt of notifications.

2.Observable Operators

With the help of Rx java API,we can create,transform and perform multiple operations on Observable stream.Some of the Operators are as follows:
  • map() , a method which transforms the items emitted by an Observable by applying a function to each of them.
  • buffer(), a method which periodically gathers items from an Observable into bundles and emits these bundles rather than emitting the items one at a time.
  • scan(), a method which applies a function to each item emitted by an Observable, sequentially, and emits each successive value.
  • observeOn(), a method which specifies on which Scheduler a Subscriber should observe the Observable.
  • filter(), a method which filters items emitted by an Observable,last(), a method which emits only the last item emitted by an Observable.
Example of Rx java for API call using retrofit:


Observable<String> observable= Observable.just("Lets Start");





That's all for now,I hope it might help you.Now you can start with implementation of Rx java with your application.Thanks for reading,will get back soon with something new.Don't forget to share your feedback.





Comments

Popular posts from this blog

Android Studio and its UI performance measuring features

Android studio Tools for UI/UX and enhanced performance of app

BuzzNews for Android Devs: Android Studio 3.0 RC1