Creating a unique RXJS pipe that takes in an observable and holds off until said observable satisfies a specific criterion

Check out the code snippet below:

export function featureComplete(feature: BaseFeatureService) {
  return pipe(
    combineLatest([feature.loading$]),
    filter(([input, loading]) => !loading),
    map(([input, loading]) => {
      return input;
    })
  );
}

To use this function, simply modify your observable like so:

observable$.pipe(
   featureComplete(this.propertyFeatureService)
);

The combineLatest operator should be used instead of zip, as the latter is deprecated. This adjustment will ensure that your solution continues to work effectively.

If you prefer, you can also pass in an `Observable` for the waiting condition by using feature.loading$.

Thank you for considering these alternatives!

Answer №1

After exploring other operators, I stumbled upon withLatestFrom, which serves the same purpose as the zip operator mentioned earlier.

The revised code block now appears as follows:

export function featureReady(feature: BaseFeatureService) {
  return pipe(
    withLatestFrom(feature.loading$),
    filter(([inputObject, loading]) => !loading),
    map(([inputObject, loading]) => {
      return inputObject;
    })
  );
}

I will keep the question open in case someone can suggest a more efficient solution.

Answer №2

Utilizing the skipUntil Rxjs pipeable operator is recommended as it allows skipping values until a specific condition is met by the inner observable.

In the code snippet below, the source Observable will wait for the function `fun` to return a custom pipe that will continue waiting until the inner observable indicates that the loading status is false.

const { interval, timer,of,concat } = rxjs;
const {  skipUntil,delay,filter,ta } = rxjs.operators;


// TypeScript code goes here!
const appDiv = document.getElementById('app');
appDiv.innerHTML = `<h1>Wait until the loading status is false</h1>`;

//custom pipe function which will wait until loading status is false
const fun = (wait1) =>  skipUntil(wait1.pipe(filter(status => !status['loading'])));

console.clear()
const status = [{loading:true},{loading:false}]
//emit every 1s
const source = interval(1000);

// inner obserbale which will emit the status after certain intervals
const wait1 = concat(of(status[0]).pipe(delay(1000)),of(status[1]).pipe(delay(3000))).pipe(delay(5000));
//skip emitted values from source until inner observable emits false after the loading status turns to false
const example = source.pipe(fun(wait1));

const subscribe = example.subscribe(val => appDiv.innerHTML += 'interval ' + val + '<br/>');
const subscribe1 = wait1.subscribe(val => appDiv.innerHTML += 'inner Observable status ' + val.loading + '<br/>');
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>

<div id="app"></div>

For the StackBlitz solution, click here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to transform an object into an array consisting of multiple objects in TypeScript

The car's details are stored as: var car = {model: 'Rav4', Brand: 'Tayota'} I need to convert this information to an array format like [{model: 'Rav4', Brand: 'Tayota'}] ...

Having trouble with image loading in NextJS after replacing an old image with a new one?

I have been attempting to swap out my current banner with different images to test if they work, but every image I try leads to an error when using next/image or even a simple <image> tag. The error message states that "The requested resource isn&apo ...

What is the reason for the HTTP service being activated automatically?

Utilizing the Http service, data is fetched and then passed into the cached service. The component subscribes to the cached service and initiates the HTTP request. The HTTP GET service is intended to be called when the user clicks on an anchor tag. Upon c ...

A function in Typescript that can handle dynamic keys and values using generics

function convertArrayToObject<T>(array: T[], key: keyof T): Record<string, T> { return array.reduce( (accumulator: Record<string, T>, currentValue: T) => Object.assign(accumulator, { [String(currentValue[key])]: cur ...

What could be causing the malfunction when using TypeScript's generic T with any?

The playground demo The diff: A: function<T extends { status: number }> () {} B: function<T = any> () {} the B does not have access to T's property, while the A function only accesses T's status. Thank you ...

Optimal method for populating table filter values from query string in Typescript while handling asynchronous calls

Using Typescript for Angular, I am dealing with a table that has filters in the form of drop downs. The data for each filter is retrieved asynchronously from the backend. My challenge is to load the data for all filters while setting default values based o ...

Modifying the value of a React input component is restricted when the "value" field is utilized

I'm currently utilizing material-UI in my React application. I am facing a challenge where I need to remove the value in an input field by clicking on another component. The issue arises when using the OutlinedInput component with a specified value. ...

generate a fresh array with matching keys

Here is an example array: subjectWithTopics = [ {subjectName:"maths", topicName : "topic1 of maths " }, {subjectName:"maths", topicName : "topic2 of maths " }, {subjectName:"English", topicName : &quo ...

When trying to install my npm package from the registry, I keep encountering an issue despite being able to install it locally

I recently released my Node.js/typescript package on the npm registry, but I'm encountering issues when trying to install it from there. Oddly enough, local installation works perfectly fine. Here's the output from the local installation: $ npm ...

Leveraging foreign key attributes within Angular templates

My technology stack includes Django for the backend with Django Rest Framework and Angular for the frontend. Within the backend, I have defined 2 models: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null= ...

Exploring cutting-edge Angular 2 UI controls?

Imagine this scenario: An extensive organization is in need of developing a large web application with advanced UI components, such as hierarchical grid/tree and charts, alongside the standard UI elements. All these controls should ideally be sourced fro ...

Converting ts files to js: A comprehensive guide

I am looking for a way to transform my TypeScript files into JavaScript files smoothly. The conversion process goes well with the command: nodemon --watch assets/ts --exec tsc assets/ts/*.ts --outDir assets/js However, I have encountered an issue where im ...

Is a loading screen necessary when setting up the Stripe API for the checkout session?

While working on my web app and implementing the Stripe API for creating a checkout session, I encountered an issue where there is a white screen displayed awkwardly when navigating to the Stripe page for payments. The technology stack I am using is NextJ ...

The method this.object.remove does not exist

I'm encountering a situation that closely resembles this Runtime Error this.object.remove is not a function. Despite following the suggested solution, I'm still facing issues. The specific error message I'm getting is this.menuData.remove i ...

Tips for transferring information between service functions in Angular

In my front-end development, I am working on creating a store() function that adds a new question to the database. However, I need to include the active user's ID in the question data before sending it to the back-end. Below is the code for the store ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

How is it that in TypeScript, a potential numeric value in an interface can be transformed into an impossible numeric value in a class implementation?

Encountered a surprising behavior from the TypeScript compiler today. Unsure if it's a bug or intentional feature. If it is indeed intentional, I would like to understand the reasoning behind it. The issue arises when declaring an interface method wi ...

Is it possible to move around in an Angular SPA to different html pages without needing to create a new

How can I incorporate static content, such as a privacy policy, into my ASP.NET Core Angular SPA in a way that ensures it is displayed seamlessly within the application rather than as a separate static HTML page? Is there a strategy to achieve this withou ...

Creating various import patterns and enhancing Intellisense with Typescript coding

I've been facing challenges while updating some JavaScript modules to TypeScript while maintaining compatibility with older projects. These older projects utilize the commonjs pattern const fn = require('mod');, which I still need to accommo ...

Error in Angular 6: Unable to access property 'mapName' as it is undefined

For my web project using the Mean Stack with Angular 6, I need to create a form that includes an uploaded file. Below is the HTML code snippet: <ng-template #content let-c="close" let-d="dismiss"> <div class="modal-header"> <h4 class= ...