RxJS Retrieve Related Data Pipeline Explained

Introduction

In this series of posts, we will cover few common RxJS pipeline and example code for practical usages.

  • Retrieve Related Data Pipeline
  • Lookup Reference Property Pipeline
  • Grouping Pipeline
  • Auto Complete Pipeline

In this post, we’ll cover the Retrieve Related Data Pipeline. Upcoming posts will cover the other topics. So let’s start.

Retrieve Related Data Pipeline

Example: We have a search-box where we can enter a user-name and show all posts for that user.

Challenge: Our Post model have user-id while we enter user-name for search.

So, how do we deal with it?

Answer:

We’re going to first have to get the user, so that we can lookup the user-name, get the id and then lookup the posts for that user-id. So, here we are retrieving related data for the user.

Solution

Whenever, we hear an action or think action, we can use a Subject or BehaviorSubject.

Pipeline

so, we searched for users based on searchTerm, and next we want to do is, to take the users and we’re going to pull of the first user because we are assuming that our username would only match one user and that’s the user’s id that we want and we use that go get our posts (second switchMap) or optionally, we can pass a default value when no users are found.

Following are results

search-1

search-2

Breaking down in reusable parts

If we see our above code, its getting complicated and it is currently without any error handling and if we need reuse then its difficult to do so.

So, lets break down it a little further as follows

and now the code is more clean and easy to reuse and extend further if needed.

Summary

In this post, we saw the examples of RxJS implementation of Retrieve Related Data Pipeline. We also learned that how to simplify a pipeline by breaking it apart in smaller reusable pieces. Let me know if you have any questions and comments. Till next time, Happy Coding!