Reactive Programming and the RX (r)evolution


whoami

A Software Architect with over 25 years of experience.

 

CTO in Softphone and Cofounder of SoulSofware company.

 

an active contributor to  the open source eco-system. https://github.com/bsorrentino

 

 

          http://soulsoftware-bsc.blogspot.it/

       https://twitter.com/bsorrentinoJ

                https://www.linkedin.com/in/bartolomeosorrentino

           https://plus.google.com/+BartolomeoSorrentino

briefly overview of

The Reactive Manifesto

Published in 2014 the Reactive manifesto refers to Reactive System as system that are more flexible, loosely-coupled and scalable.

 

Such system must be:

  • Responsive
  • Resilient
  • Elastic
  • Message Driven

Reactive Manifesto - Reactive System

The Reactive Manifesto introduces a

"tech. agnostic shared vocabulary"

that will help us to better understand the concepts that we will meet during our knowledge acquisition path:  

 

The main terms are:

  • Asynchronous
  • Non-Blocking
  • Back-Pressure
  • Delegate Errors

Reactive Manifesto Vocabulary

Why

Reactive Programming

to handle which need

To build Applications that:

  • React to event   => event driven

  • React to load     => Scalable

  • React to failure => Resilient

  • React to user    => Responsive

so ... how to achieve this ?

Let's do it

ASYNCHRONOUS 

but avoiding as much as possible to deal with threads (if any) .

 

Async != multi threads

Async == never block 

 

use threads

  • Code that is non-deterministic

  • Share mutable-states imply heavily use on synchronisation stuff

  • The greater part of Application's threads are in waiting state

  • Threads limit vertical scalability  

drawbacks

Reactive is never block

  • Never sit on resources you don’t use

  • Use non-blocking IO

  • Use lock-free concurrency 

  • ...unless you really have to

  • Blocking kills scalability (& performance)

Design a Reactive App

  • Use asynchronous event/message passing
  • Think in workflow, how the events flow in the system

and gets ....

  1. lower latency
  2. better throughput
  3. a more loosely coupled architecture, easier to extend, evolve & maintain

...... BLA, BLA, BLA ..........

from developer perspective 

  • Deal with "functional programming" approach

  • Deal with "immutable state" concept

  • Deal with "asynchronous workflow

programming

PARADIGM !!!

yet

Another

But

Don't worry

Reactive Programming promises to be fun in developing and provides  
an awesome way to write ultra-responsive code, orchestrating  a bunch of diverse asynchronous operations into one beautiful, declarative and concise set of instructions.

        searchResultsUpdatingSubject
        .filter( { (filter:String) -> Bool in
            
            return filter.characters.count > 2
        })
        .distinctUntilChanged()
        .debounce(debounce, scheduler: MainScheduler.instance)
        .flatMap( {  (filterString) -> Observable<NSData> in        
            
            return slideshareSearch( apiKey: credentials["apiKey"], 
                                     sharedSecret: credentials["sharedSecret"], 
                                     what: filterString )
        })
        .flatMap({ (data:NSData) -> Observable<Slideshow> in
         
            self.filteredDataItems.removeAll()            
            let slidehareItemsParser = SlideshareItemsParser()
            return slidehareItemsParser.rx_parse(data)
        })
        .filter({ (slide:Slideshow) -> Bool in
         
            if let format = slide["format"] {
                return format.lowercaseString=="pdf";
            }
            return true
        })
        .observeOn(MainScheduler.instance)
        .subscribe({ e in
            
            if let slide = e.element {   
                self.filteredDataItems.append(slide)                
                let title = slide["title"]
                self.collectionView?.reloadData()
            }            
        }).addDisposableTo(disposeBag)
 

When

Reactive Programming

When and how It could help you

 

Client Side 

To Be Reactive ... never block

 

  • Single Page Application (Angular, React, ...)
  • Mobile Application (Android, IOS)
  • Desktop Application (WPF,SWING,...)
     

More in general in every User Interaction based Application

 

Server Side

Achieve Seamlessly Vertical & Horizontal Scalability

 

  • Non-blocking I/O
    • WebSocket, Messaging, Notification, Streaming
    • Java Backend using Servlet 3.1
    • NodeJS BackEnd
  • Complex Systems' Integration Scenarios (REST,JMS,SOAP,...)

I’ve heard a good argument about when to use reactive programming to develop solutions

 

 

 

 

They say ...

 under a certain level of complexity in the code, reactive makes it even more complex, but after a point, it makes complex code simpler.

Path toward RFP

start to Develop:

1)  Fluently
     (use Builder Pattern)

2) Fluently + Functional
    (use and abuse of lamdba)

3) Fluently + Functional + Asynchronous
    (use MessageLoop and Scheduler)

Reactive Programming

Key Concepts

Adopt Reactive Programming  means developing using asynchronous data stream

The closer concept to asynchronous data stream is 

"Iterate on collection over time"  

But, since we have deal with time dimension, in Reactive Programming instead of "Iterate over data" we have to "Observe for event"

The effectiveness of Reactive Programming  depends by ability to create streams of anything: variables, user inputs, properties, caches, data structures, network & system events, etc. 

Design Patterns

Here the famous design patterns that everyone known .

 but not always everyone apply

Reactive Distillate 
Design Patterns 

Here the only patterns need to be reactive:

Iterator

To iterate over data in one way

Observer

To handle and process data

Builder:

To achieve fluently and expressive code 

Reactive Programming is an improved alternative to the Observer Pattern that's designed to deal with events as a stream of values over time rather than as a series of unique responses to discrete changes in state.

 

This helps to deal with complex logic behind the event handling code with no loss of expressiveness.

 

It is useful anywhere the Observer pattern is common, including user interfaces, video games, networking, and industrial applications.

Iterable Observable
Pull Push
T next() onNext(T)
Throws E OnError(E)
return onCompleted()

I have a Stream

Observable Async. Data Stream

The Marble Diagram

A great way to represent stream processing

From Sequence to Marble Diagrams

Operators

The Core of the RX that enable stream processing through function composition

 

You have to know how properly applying them to achieve the powerful of RX 

Operators By Categories  

  • Creating  Operators that originate new Observables.
  • Transforming  Operators that transform items that are emitted by an Observable.

  • Filtering  Operators that selectively emit items from a source Observable.

  • Combining  Operators that work with multiple source Observables to create a single Observable

  • Error Handling  Operators that help to recover from error notifications from an Observable

  • Observable Utility  A toolbox of useful Operators for working with Observables

  • Conditional and Boolean  Operators that evaluate one or more Observables or items emitted
  • Mathematical and Aggregate  Operators that operate on the entire sequence of items emitted by an Observable
  • Backpressure — Strategies for coping with Observables that produce items more rapidly than their observers consume them
  • Connectable  Specialty Observables that have more precisely-controlled subscription dynamics
  • ConvertConvert Observables into another objects or data structures

Operators' Land

Playgrounds                                                      

- http://rxmarbles.com/                    

- http://users.telenet.be/jo.van.den.berghe/rx/

HOT 

vs

COLD

OBSERVABLE

How to develop using Reactive Programming?

The Reactive Extension

RX

RX: where is supported it 

Languages

 

Platforms and frameworks

Most programmers exposes programming using term like: "triggering", "updating", "dispatching", "firing" methods and procedures.

 

Those are idioms and techniques opposite to reactive programming, where instead we try to declare what is "triggered by" or "updated by". (from message to event)

 

The biggest challenge is simply to go through the mental revolution from "A changes B" to "B is changed by A". After that, the smaller challenges are learning Rx operators, where they apply, and common techniques. >>

Mind Change & Challenges

LET'S CODE