What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without being buffered.

// Example: emitting a value every 1 second
// 0,1,2,3,4,5...
const source = interval(1000);

// Buffer values for 4 seconds
const buffered = source.pipe(
  buffer(interval(4000)),
  filter(x => x.length > 0)  
);

const subscribe = buffered.subscribe(val => console.log(val));

The expected outcome should be:

[0,1,2,3] // Emits after 4 seconds
[5] // Emits immediately
[4,6,7,8] // Emits after 4 seconds
[10] // Emits immediately
[9,11,12,13]
// ...and so forth

See it in action on Stackblitz: https://stackblitz.com/edit/typescript-cdvc2d?file=index.ts

Answer №1

What if we created two observables with distinct responsibilities and then combined them together?

const source = interval(1000);

// buffer values for 4 seconds
const buffered = source.pipe(
  buffer(interval(4000)),
  filter(x => x.length > 0)  
);

const multipleOfFive = source.pipe(
  filter(x => x % 5 === 0)
);

const subscribe = merge(buffered, multipleOfFive).subscribe(val => console.log(val));

I'm considering filtering out the multiples of 5 in the first observable as well, which is easily achievable.

Answer №2

If you want to divide the original stream into two parts and then combine them again using different filtering methods, you can utilize the multicast function.

import { of, interval, Subject, merge } from 'rxjs';
import { bufferTime, multicast, filter } from 'rxjs/operators';

const buffered = source.pipe(
  multicast(new Subject(), s => merge(
    s.pipe(
      filter((value: number) => value % 5 === 0),
    ),
    s.pipe(
      filter((value: number) => value % 5 !== 0),
      bufferTime(4000),
    ),
  ))
);

To see a demonstration of this concept in action, check out the updated demo here: https://stackblitz.com/edit/typescript-sbhn8s?file=index.ts

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

Can this pagination task be accomplished without the use of backgrid?

I have been exploring ways to implement server-side pagination similar to what Datatables offers, and during my search I came across the backbone.paginator library on GitHub. However, I am curious if there are any other options available as well. After ex ...

Setting the date of the NgbDatePicker through code

I have implemented two NgbDatePicker components in my project: input( type="text", ngbDatepicker, #d="ngbDatepicker", [readonly]="true", formControlName='startDate', (dateSelect)='setNew ...

Having trouble with dragging a file from one box to another in HTML5. The functionality is not working

Encountering an issue where the image does not display in the left box after dropping it. Here is the sequence of events: Before dragging the image: After dragging the image, it fails to display: The error reported on Chrome is as follows: GET file:/// ...

Troubleshooting webpack encore issues with importing enums from node_modules

I am faced with a challenge of utilizing an enum from a library I created in a different project. The library is developed using Vue and typescript, bundled with rollup. On the other hand, the project is built with Symfony, with the front end also using Vu ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

Issue with NGXS Selector Observable not reflecting updated state

My issue is that when I update the state, my selector does not pull the new values. I have defined the selector in my state and I can see the state values getting updated. However, the selector in my component is not fetching the latest values. Even though ...

Issues may arise in Typescript when trying to return an array of data from a redux createAsyncThunk function

Below is the code I am using to retrieve a list of users: export const fetchUserById = createAsyncThunk( "users/fetchById", async (_, { rejectWithValue, fulfillWithValue }) => { try { const response = await fetch(`https://reqres. ...

Using dropzone.js on multiple files in a single webpage

Is it feasible to incorporate multiple dropzone elements on one webpage instead of having numerous file uploads on a single dropzone element? It appears that dropzone fails to trigger after the selection dialog box when there are several elements, each wi ...

Contrast between pm.response.json() and parsing the responseBody using JSON.parse()

Can you explain the key distinction between const json_response = pm.response.json() and json_response = JSON.parse(responseBody) ...

Transmitting information from JavaScript to a PHP script

I am currently using a function that grabs text from a PHP file on our server and inserts it into an HTML page. However, I now need to modify this function in order to SEND data (specifically a couple of JavaScript variables) to the PHP file instead of si ...

Error Event Triggered by AJAX with No Response Data

I am currently facing an issue with an API call I am making. Everything seems to be working fine as I receive the token and a status code of 200 is returned (confirmed in Fiddler). However, the problem arises when the AjaxError event fires and the respon ...

What's the best way to retrieve the id or index of a card within a list?

Struggling to fetch the id's of documents retrieved from a MongoDB database and displayed on React and Material-Ui cards. Tried logging id in functions and APIs, but receiving 'undefined' or metadata from the delete function. Delete functi ...

Implementing RequireJS Singleton pattern with Web Workers

I'm currently working on a JavaScript project that utilizes the latest version of RequireJS. One of the modules I am defining is chessWorker, as shown below: var worker; define("chessWorker", ["jquery", "messageListener"], function($, listener) { ...

What is the best method to substitute a comma and period with just a period in a textarea

Creating a text area with auto-replacing characters like straight quotes, double dashes to em dash, and double spaces to single space was simple. However, I'm facing difficulty in adding a script for replacing certain characters: word . as word. wor ...

Experiencing Strange Issues with Jquery Image Carousel... Assistance Needed!

I recently created a jquery slideshow using a tutorial I found at this link: While the slideshow is functioning correctly for the most part, there is a strange issue that occurs right at the beginning when displaying the first image. Initially, the first ...

Removing a parameter from a variable in jQuery and JavaScript

I have coded something and assigned it to a variable. I now want to replace that value with another one. Just so you know, I do most of my coding in perl. Specifically, I am looking to remove the menu_mode value. Any advice on this would be greatly appre ...

Tips for real-time content updates on a server-side rendered express application

My social media app, built using Express, Pug, and JavaScript for server-side rendering, is fully functional. However, whenever I comment on a post, I need to manually reload the page to see the new comment displayed. I'm exploring ways to dynamicall ...

Steps to reinitialize the error code after removal from the roster

Currently, I am working on creating a series of textboxes and dropdown menus using jQuery. So far, the add function is functioning smoothly without any glitches. However, my issue lies within the delete function. It works well when deleting sequentially, ...

Experiment with the Users.Get function available in vk-io

I am having an issue with a create command: Ban [@durov] and I encountered an error. Here is how I attempted to solve the problem: let uid = `${message.$match[1]}` let rrr = uid.includes('@') if(rrr == true){ let realid = uid.replace(/[@]/g, &ap ...

Implementing a persistent "remember me" feature in Angular 2 without relying on local

Is it possible to implement a "remember me" feature in Angular 2 without relying on the use of local storage? ...