RxJS Pattern: Asynchronous data sharing with AsyncSubject

Today I want to talk about an RxJS pattern that I use quite often when I need to access asynchronously loaded data from components that don't know when and how the data is retrieved.

A typical scenario would be when you have one part of the page/app that owns the data and is responsible for retrieving it (let's call it Component A) and then you have another part (or many parts) of the page that does something with that data, but it doesn't care where the data comes from, it just needs to get it when available (let's call it Component B).

In this scenario RxJS becomes very handy since it provides the Observable interface that the Component B can use to get the data without knowing where it comes from.

Let's look at a more concrete example using Angular. Suppose we have an app with a main content and a sidebar. The main content component will load a list of items on a certain user action (like a button click) and the sidebar component will display the number of items once the data is available.

Note: I use Angular for this example, but the concepts described in this post are not specific to Angular and are applicable to any app that can use RxJS.

As you can see, SidebarComponent doesn't know where the data comes from, when it is loaded and so on. It only knows that the data comes in a form of Observable<Data>. This is very convenient because we don't need to worry about accessing the data before it is initialized, we can use the RxJS operators to perform any kind of transformations and bind to it directly in the template via the async pipe.