Indicate when a ReplaySubject has reached its "completion" signal

I'm currently looking for an effective way to indicate when a ReplaySubject is empty.

import {ReplaySubject} from 'rxjs/ReplaySubject'; 
const rs = new ReplaySubject<Object>();

 // ...
constructor(){
  this.sub = rs.subscribe(...);
}

Each time the constructor is called, all items from the subject are replayed. But my main question is - is there any event we can monitor to know when the subject is empty?

The only solution I can come up with is triggering a custom event when the subject is done, like so:

rs.next({done:true});

Is sending data to the next() method the most effective way to signal that the ReplaySubject is temporarily empty or out of events?

Answer №1

When Subject is functioning as an Observer, you have the option to trigger complete() right after the last next() call. This way, you can monitor it using the third parameter of the subscribe(...) method.

const rs = new ReplaySubject<Object>();
rs.next({a: 1})
rs.complete()

rs.subscribe(
    obj => console.log(obj),
    error => {},
    () => console.log('completed')
);
// Result
// {a: 1} completed

Answer №2

One approach could be to create a secondary observable to keep track of the last item being replayed:

const last$ = rs.replay(1);

Then, by using combineLatest and scan, you can monitor when the ReplaySubject has completed replaying:

this.sub = Observable.combineLatest(
  rs,
  last$.take(1)
).scan((acc: { item: Object, isReplay: boolean }, curr: [Object, Object]) => {
    return {item: curr[0], isReplay: acc.isReplay && curr[0] !== curr[1]};
  }, {isReplay: true}
).subscribe(...);

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

Using the VSCode debugger to place a breakpoint within a Typescript package that has been symlinked using `npm link`

I'm currently troubleshooting a NodeJS application and its associated typescript packages, which have been linked using `npm link`. The directory structure is as follows: /root/package-a # typescript package /root/package-b # another typescript packa ...

Is it possible to activate every function within a prototype?

When presented with a class structure as demonstrated below, I am able to iterate through all its PropertyNames using console.log. class Security { constructor(param: ParamType) { this.method1(param); ... this.methodN(param); } method1(p ...

Hide react component by clicking it

There is a cookies component with a button labeled "I agree" that I want to use to close the component when clicked. However, I am facing an issue in getting this functionality to work. I understand that the onClick event on the button should trigger an ...

Guide on using the Swagger Codegen TypeScript Fetch Client

I'm in need of assistance with utilizing the Swagger Code Generator to create a TypeScript Fetch client suitable for browser use. Specifically, I am attempting to integrate the generated API client into a TypeScript-based React application. After suc ...

Issue: NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper]:

While I am going through a tutorial on the abp framework, I encountered an error with the Author route that says "ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelp ...

"Encountering issues with running a MongoDB aggregate query involving date fields

I have been attempting to retrieve data from MongoDB using an aggregate query in Node.js for a specific date range. let date = '20230925' let year = date.slice(0, 4); let month = String(date.slice(4, 6)).padStart(2, '0'); ...

Experimenting with a TypeScript custom hook for React testing

I have successfully created a customized hook called useForm using TypeScript and it is functioning properly. I have tested it with @testing-library/react-hooks and the tests have passed. However, TypeScript is flagging an issue in a specific location - as ...

Viewing the photo container before uploading while having text overlap

I'm encountering an issue where the image previews are overlapping with the text in another div. Here are the screenshots: the first one shows how it looks before the preview, and the second one shows what happens when images are added: https://i.sst ...

Showing dynamic icons in Angular 2 applications

My goal is to dynamically load a part of my website, specifically by using icon classes defined in the interface like this: import { OpaqueToken } from "@angular/core"; import {IAppConfig} from './app.interface' export let APP_CONFIG = new Opaq ...

When using TypeScript with custom components as children in React, the `type` returned by React.Children is a string representing the function

It might sound a bit odd, or maybe I'm completely off track here. While going through some articles and React documentation on getting children and identifying specific child components using React.Component.map(), I ran into an issue with my custom c ...

Issue with Angular Swiper carousel: Error message pointing to node_modules/swiper/angular/angular/src/swiper-events.d.ts

I am attempting to implement a carousel in Angular using Swiper (). An error message is appearing: Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts:3:50 - error TS2344: Type 'SwiperEvents[Property]' does not meet the constraint ...

Ionic is throwing a reference error stating that __importDefault is not defined

My project is encountering the following error when I try to run it: Uncaught ReferenceError: __importDefault is not defined at Module../src/app/app.component.ts (app.component.ts:9) at __webpack_require__ (bootstrap:84) at Module../src/app/app.module.ts ...

Deciphering the .vimrc setup for tooltips and symbols in TypeScript

Currently, I have integrated the Tsuquyomi plugin for my typescript development in Vim. The documentation mentions tooltips for symbols under the cursor, which are working fine. The issue arises as I am using terminal-based Vim, and even if I were using a ...

Encountering an issue saving files in Angular 2 when the npm server is active

Encountering an issue when trying to save .ts or .html files while npm is running 1: DoJoin(aka DoJoin) [native array.js:~129] [pc=0000035BB365DBB2] (this=0000005A3F604381 <undefined>,w=000003CB8840CFF1 <JS Array[104]>,x=104,N=0000005A3F6 ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...

Compiling errors arise due to TypeScript 2.4 Generic Inference

Experiencing issues with existing TypeScript code breaking due to changes in generic inference. For instance: interface Task { num: number; } interface MyTask extends Task { description: string; } interface Job {} type Executor<J> = <T ...

Leveraging getStaticProps in Next.js

I am currently embarking on my inaugural Nextjs project, focused on developing a basic blog utilizing the JSON placeholder API. Strangely, I am encountering an issue where the prop "posts" is being perceived as undefined. Can anyone provide assistance with ...

Is it possible for decorators to invoke services within an Angular application?

Recently, I've delved into exploring decorators for TypeScript. Angular showcases a wide array of decorators like Components, Injectables, Directives, and more. I find myself frequently repeating a logic block that checks if a user is logged in and au ...

Using Typescript to extract values from an array and apply them as filters on a Map

My code involves two maps: charamap and filterdata. The goal is to filter charamap so that it only displays data for items listed in filterdata. The expected result should be: [LOG]: ["Football":1, "Golf":0] However, the actual output is: [LOG]: ["Footba ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...