Controlling Data Streams

Learn how to create a centralized service that will serve as a switch between application modes, including work mode and view mode.

Work/view mode use case

In this lesson, we will go through a very common scenario when building web applications. Suppose that you are building a SPA web application- a web-based image editor similar to Photoshop that will work in two modes: work Mode and view Mode. It will have several components that must communicate with each other by exchanging keyboard and mouse events, HTTP requests, etc.

When in work mode, every kind of communication between components must take place (with every keyboard and mouse event handled accordingly), and the appropriate action should be triggered.

When in view mode, the event handlers should be disabled so that no action is triggered on any keyboard or mouse events (or the interested subscribers should not be able to listen).

Finally, you must provide a way to allow switching from one mode to another, in most cases, via a switch button.

Solution overview

The solution might seem pretty simple at first glance. When clicking the switch mode button (work mode), every subscriber to the event emitters should unsubscribe, and when switching to view mode, every old subscriber should re-subscribe to listen to the mouse and keyboard events.

Now, imagine the scenario where you have multiple components that are interested in keyboard or mouse events. What would happen when more diverse events take place, like HTTP calls, socket subscriptions, and so on? Applying the above-mentioned solution for every use case is not appropriate, nor it is scalable.

What we need in this case is a centralized place where we can control the data stream by toggling the values it emits. Every interested component could subscribe to the controlled data stream and only receive values when the data stream is active.

On the other hand, the component that contains the mode toggle button will enable or disable the controlled data stream.

To centralize the data stream control, we will create a centralized service that can be injected into any interested component. The use case is illustrated below:

Get hands-on with 1200+ tech skills courses.