A RxJS function that emits the final value from the first observable and then emits true from the second observable

Hello, I'm attempting to design a function that involves an observable (OBS) and a subject (SUB). The goal is to capture the last item from OBS while SUB is in state F, and then emit this particular value only when SUB transitions to state T.

   OBS ---a----b----c----d----e----f----g----h-----
   SUB ------F----------T------------F-------T-----
   OUT -----------------c--------------------h-----

I have attempted to tackle this challenge with the following code:

OBS.window(SUB)
        .withLatestFrom(SUB)
        .switchMap(([window, status]) => {

            if(status === F) {
                return window.combineLatest(SUB, (cmd, status) => {
                    if(status === T) {
                        return null;
                    };

                    return cmd;
                }).last((e) => {
                    return !!e;
                })
            }

            return Observable.empty<Command>();
        }).filter((cmd) => {
            return !!cmd;
        })

Unfortunately, the solution does not seem to be working as expected.

Answer №1

Looks like you're after something along these lines:

SUB
  // Ensure only changes in status are emitted
  .distinctUntilChanged()
  // Pass only true values downstream
  .filter(value => value === TRUE)
  // Emit the latest value from OBS when a TRUE is received from SUB
  // Remap it to forward only the command
  .withLatestFrom(OBS, (_, command) => command)

Answer №2

I came up with my own solution:

OBS
    .buffer(SUB)
    .withLatestFrom(SUB)
    .map(([buffer, t]) => {
        if(!buffer || !buffer.length) {
            return null;
        }

        if(t === T) {
            return buffer[buffer.length - 1];
        }

        return null;
    })
    .filter((e) => !!e);

This version demonstrates the following behavior:

 ---a----b----c----d----e----f----g----h-----
 ------F----------T------------F-------T-----
 -----------------c--------------------h-----

It does not generate output if the window between F and T is empty

 ---a--------------d----e----f----g----h-----
 ------F----------T------------F-------T-----
 --------------------------------------h-----

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

What is the significance of enclosing Button within CardActions in Material-UI?

As I explored the Card documentation on MUI, I found that the Button inside the card is always enclosed within CardActions. However, I couldn't quite grasp the purpose of this tag as it wasn't clearly explained in the documentation. The only noti ...

Accessing properties like $vuetify using getCurrentInstance() in Vue 2.7

Currently, I am in the process of upgrading from vuetify 2.6 to 2.7 for the composition-api functionality. However, I am encountering numerous errors when attempting to access properties of the Vue instance. For example, I am using Vue with Vuetify and hav ...

Having trouble with HTML - JavaScript function not processing responseText?

On my website, there is a button array that displays the position of a robot by reading a text file using a php/ajax combo. The script initially sets all buttons to the same color and changes the color of the button to represent the robot's position. ...

Guide on achieving mirror effect with cursor on a webpage

Is it feasible to achieve a cursor mirroring effect on a website using Javascript, or similar technology? Imagine a scenario where the line dividing the black and white sections of the page serves as the "reflection line." In this setup, moving the cursor ...

Implementing Highcharts in AngularJS with dynamic variables directly in the code (leveraging Pablojim's Highchart-ng library)

Currently, I am utilizing the Highchart charting library in conjunction with AngularJS by employing Pablojim's 'Highchart-ng' module. The setup is correct, and the following code functions as expected: <highchart config="{ type : ...

Combine an empty array in JavaScript with the existing array to eliminate the current items

Is there a more effective way to merge arrays and update state based on the array received from the server? The array may be empty, which would result in removing all values from the state individually. My objective is to update a new state depending on t ...

How to achieve a seamless iframe effect using CSS

With the introduction of new HTML5 iframe attributes, there are now more options available. One such attribute is the seamless attribute, which has the ability to: Create an iframe that appears to be seamlessly integrated into the containing document. ...

Image linking

In my Vue component, I have an img tag with a bound src attribute that references Vuex state. <img :src="this.$store.state.imageDataURI"> I am able to successfully update the state object in Vuex as shown below. However, the img tag is not being r ...

The code is throwing an error stating: "TransformStream" is not a recognized name

I'm encountering an issue with my socket.io code. It previously built without any problems, but now I am unsure about what changes have caused the build to fail. It seems that TransformStream, a native node library, is having trouble loading in Typesc ...

Having trouble with selecting JS dropdown options in Python Selenium

My HTML view- Check out the website design HTML code- View the HTML code here When I click on the dropdown arrow, a new code appears - view the code snippet Although my code successfully displays the dropdown options, it does not allow for selecting an ...

Mastering the art of using the async pipe in conjunction with rxjs

I require assistance as the loading component of my async pipe does not activate, despite the data loading correctly. The loading template fails to trigger during subscription even though I am using a BehaviorSubject in my service. I have attempted various ...

Sharing data between child and parent components, and then passing it on to another child component in React Js

I have a scenario where I am passing props from a child component B to parent component A, and then from parent component A to child component C. Everything works fine when I pass the data from component B to A, but I encounter an issue when I try to set a ...

What sets apart Records and Objects in TypeScript?

I am exploring how to define a conditional type in TypeScript that can differentiate between "record" types (with dynamic/unbounded keys) and plain object types (with predefined keys). type R = { [x: string]: any } type O = { a: string; b: number } One ap ...

A practical guide to effectively mocking named exports in Jest using Typescript

Attempting to Jest mock the UserService. Here is a snippet of the service: // UserService.ts export const create = async body => { ... save data to database ... } export const getById = async id => { ... retrieve user from database ... } The ...

The Checkbox handler in Material-UI component fails to update the state - Version 5.0

Hey everyone, I'm facing an issue with my "Checkbox" component in React. After clicking on it, the state doesn't update to 'true' as expected. The checkbox works visually in the DOM but the state remains 'false'. Can someone p ...

The page is not responding after closing the modal dialog

My web application is built using Spring Boot for the backend and Thymeleaf for the front end. The app displays all available groups for users to review. When a user clicks on a group, the documents within that group are listed in a tabular form. Clicking ...

Unable to modify the Express Request User type, however, I have the ability to incorporate new attributes to Request object

Encountering a familiar issue with what appears to be a simple fix. The Express Request object includes a user property that is specified as Express.User (an empty object). Attempting the common approach to redefining it: // index.d.ts import { User as P ...

Leveraging the outcome of a for loop in order to set a condition within an else if statement

How can I condition my third else if statement based on the result of a for loop? //If player clicks centre on first move go in corner square if (current[4] === playerToken && this.state.stepNumber === 1) { let move = c ...

Export nested objects from an AngularJS JSON array to a CSV file

When I download my data into a CSV file, the display setting is showing as "[object Object]". This is not the desired outcome. https://i.stack.imgur.com/ej2UO.png The expected display should look like this: https://i.stack.imgur.com/8JJ88.png This is p ...

Is there a way to implement a select all feature for checkboxes that have been manually toggled on and off?

I found a solution to select all check-boxes by manipulating the input elements with their class names and toggling the "checked" attribute. However, I encountered an issue where if I individually checked and unchecked any of the check-boxes, they would no ...