Welcome!

Blog Feed Post

RxJS essentials. Part 4: Using Subject

In this article I’ll introduce an RxJS Subject. The previous articles in this series include:

1. Basic Terms
2. Operators map, filter, and reduce
3. Using Observable.create()

An RxJS Subject is an object that contains the observable and observer(s). This means that you can push the data to its observer(s) using next() as well as subscribe to it. A Subject can have multiple observers, which makes it useful when you need to implement for multi-casting – emit a value to multiple subscribers.

https://yakovfain.files.wordpress.com/2017/09/appd_subject.png?w=150 150w, https://yakovfain.files.wordpress.com/2017/09/appd_subject.png?w=300 300w" sizes="(max-width: 738px) 100vw, 738px" />

Say, you have an instance of a Subject and two subscribers. If you push a value to the subject, each subscriber will receive it.

const mySubject = new Subject();

const subscription1 = mySubject.subscribe(...);

const subscription2 = mySubject.subscribe(...);

...

mySubject.next(123); // each subscriber gets 123

The following example has one Subject with two subscribers. The first value is emitted to both subscribers, and then one of them unsubscribes. The second value is emitted to one active subscriber.

const mySubject = new Subject();

const subscriber1 = mySubject
    .subscribe( x => console.log(Subscriber 1 got ${x}) ); // <1>

const subscriber2 = mySubject
    .subscribe( x => console.log(Subscriber 2 got ${x}) ); // <2>

mySubject.next(123);  // <3>

subscriber2.unsubscribe();  // <4>

mySubject.next(567);  // <5>

1. Create the first subscriber
2. Create the second subscriber
3. Push the value of 123 to subscribers (we have two of them)
4. Unsubscribe the second subscriber
5. Push the value of 567 to subscribers (we have just one now)

Running this script produces the following output on the console:

Subscriber 1 got 123
Subscriber 2 got 123
Subscriber 1 got 567

To see it in CodePen, visit the following link: https://codepen.io/yfain/pen/JyxvyK?editors=1011

Now let’s consider a more practical example. A financial firm has traders who can place orders to buy or sell stocks. Whenever the trader place an order, it has to be given to two scripts (subscribers):

1. The script that knows how to place orders with a stock exchange.
2. The script that knows how to report each order to a trade commission that keeps track of all trading activities.

The following code sample shows how to ensure that both of the above subscribers can receive the orders as soon as a trader places them. We create an instance of the Subject called orders, and whenever we invoke next() on it, both subscribers will receive the order. I’ll write this code sample in TypeScript because using types make the code easier to read/write (at least for me), but if you want to see its JavaScript version, copy/paste the code to the TypeScript playground at http://www.typescriptlang.org/play and you’ll see the ES5 version on the right.

import {Subject} from 'rxjs/Subject';

enum Action{      // <1>
    Buy = 'BUY',
    Sell = 'SELL'
}

class Order{   // <2>
    constructor(public orderId: number, public traderId: number, public stock: string, public shares: number, public action:Action){}
}

let orders = new Subject<Order>();  // <3>

class Trader {   // <4>

    constructor(private traderId:number, private traderName:string){}

    placeOrder(order: Order){
        orders.next(order);   // <5>
    }
}

let stockExchange = orders.subscribe(   // <6>
    ord => console.log(`Sending to stock exchange the order to ${ord.action} ${ord.shares} shares of ${ord.stock}`)); 
let tradeCommission = orders.subscribe(  // <7>
    ord => console.log(`Reporting to trade commission the order to ${ord.action} ${ord.shares} shares of ${ord.stock}`));

let trader = new Trader(1, 'Joe'); 
let order1 = new Order(1, 1,'IBM',100,Action.Buy);
let order2 = new Order(2, 1,'AAPL',100,Action.Sell);

trader.placeOrder( order1);   // <8>
trader.placeOrder( order2);   // <9>

1. Use enums to declare which actions are allowed for orders
2. A class representing an order
3. A subject instance that works only with the Order objects
4. A class representing a trader
5. When an order is placed, we push it to subscribers
6. A stock exchange subscriber
7. A trade commission subscriber
8. Placing the first order
9. Placing the second order

Running the above script produces the following output:

Sending to stock exchange the order to BUY 100 shares of IBM
Reporting to trade commission the order to BUY 100 shares of IBM
Sending to stock exchange the order to SELL 100 shares of AAPL
Reporting to trade commission the order to SELL 100 shares of AAPL

To see it in CodePen follow this link: https://codepen.io/yfain/pen/wqNOeg?editors=1011

In this example, we use TypeScript enums that allow defining a limited number of constants. Placing the actions to buy or sell inside an enum provides additional type checking to ensure that our script uses only the allowed actions. If we’d just use the string constants like “SELL” or “BUY”, the developer could misspell a word (e.g. “BYE”) while creating an order. By declaring enum Action we restrict possible actions to Action.Buy or Action.Sell. Trying to use Action.Bye results in a compilation error. BTW, did you know that RxJS 5 was written in TypeScript?


Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

Latest Stories
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
With the rise of DevOps, containers are at the brink of becoming a pervasive technology in Enterprise IT to accelerate application delivery for the business. When it comes to adopting containers in the enterprise, security is the highest adoption barrier. Is your organization ready to address the security risks with containers for your DevOps environment? In his session at @DevOpsSummit at 21st Cloud Expo, Chris Van Tuin, Chief Technologist, NA West at Red Hat, will discuss: The top security r...
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
IBM helps FinTechs and financial services companies build and monetize cognitive-enabled financial services apps quickly and at scale. Hosted on IBM Bluemix, IBM’s platform builds in customer insights, regulatory compliance analytics and security to help reduce development time and testing. In his session at 21st Cloud Expo, Lennart Frantzell, a Developer Advocate with IBM, will discuss how these tools simplify the time-consuming tasks of selection, mapping and data integration, allowing devel...
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...
There is huge complexity in implementing a successful digital business that requires efficient on-premise and cloud back-end infrastructure, IT and Internet of Things (IoT) data, analytics, Machine Learning, Artificial Intelligence (AI) and Digital Applications. In the data center alone, there are physical and virtual infrastructures, multiple operating systems, multiple applications and new and emerging business and technological paradigms such as cloud computing and XaaS. And then there are pe...
Today traditional IT approaches leverage well-architected compute/networking domains to control what applications can access what data, and how. DevOps includes rapid application development/deployment leveraging concepts like containerization, third-party sourced applications and databases. Such applications need access to production data for its test and iteration cycles. Data Security? That sounds like a roadblock to DevOps vs. protecting the crown jewels to those in IT.
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...