Ways to integrate an Rxjs timer with a user-triggered action

Is there a way to maintain continuous polling every 60 seconds in an observable, while also triggering the API call again when a user takes action within the component? How can this be achieved?

Below is my current setup for the polling feature:

this.covidCases$ = timer(1, 60000).pipe(
      switchMap(() =>
        this.covidService.getCovidCases().pipe(
          map(data => {
            return data.cases;
          }),
        ),
      ),
      retry(),
      shareReplay(1),
    );

I then assign this observable to the component:

<case-list [covidCases]="covidCases$"></case-list>

Answer №1

If you want to combine different streams of data, consider using the merge operator. Here is an example snippet:

    const submitButton = document.getElementById('submit');
    const clickSource = fromEvent(submitButton, 'click');
    const mappedClicks = clickSource.pipe(map(event => `Clicked at: ${event.timeStamp}`));
    // Combining button clicks and a timer. Customize as needed
    const combinedStream = merge(timer(1, 5000).pipe(map(x => 'Hello')), mappedClicks);
    combinedStream.subscribe(result => console.log(result));

Answer №2

To cater to your requirements, I recommend utilizing a combination of Subject and merge:

import { interval, Subject, merge } from 'rxjs'; 
import { mapTo } from 'rxjs/operators';

const first = interval(1000);
const subject = new Subject();

var userAction = () => {
  // perform an API call and then upon resolution
  subject.next('manual action!')
}

// combine outputs from all observables
const example = merge(
  first.pipe(mapTo('FIRST!')),
  subject.asObservable()
);
const subscribe = example.subscribe(val => console.log(val));

Check out the jsFiddle demo 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

Error encountered while parsing an Ionic template involving Ionic select, npm, and different versions of Ionic

I keep encountering the error message: ion-select-option' is not a known element. Here's what works: <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-option value="f" ...

What is the best way to choose an element within a component's template?

Is there a way to access an element that is defined in a component template? While Polymer has the $ and $$ to make this task simple, I am curious about how it can be done in Angular. Consider the example provided in the tutorial: import {Component} from ...

How can I prevent scrolling in Angular's cdk-virtual-scroll feature?

Is there a way to use Angular's cdk-virtual-scroll to prevent the scrollbar from moving by default? I have done extensive research but have not been able to find a solution. ...

There was an error while compiling the Angular application using ng serve and ng build. The error occurred in the module build and seemed to be related to the Sass loader. The specific issue was an expected "}" that was

After experimenting with various nodejs versions and npm using nvm, attempting to downgrade/upgrade ng core and ng cli, trying to install sass-node and removing sass (and vice versa), I have exhausted all options. Despite searching through numerous Stack ...

Tips on avoiding tab selection in ngx-bootstrap

My current setup includes two tabs using ngx-bootstrap as shown below. I am looking to disable the tab functionality programmatically: <tabset> <tab heading="First">Tab 1 content</tab> <tab heading="Second">Tab 2 content< ...

Develop an NPM package by bundling various Angular2 components tailored for a CRUD (Create, Read

I am new to Angular2 and have successfully developed three components for managing employees: create/edit, view, and list. The component selectors are <create-employee>, <view-employee>, <list-employee>. My goal is to create a single npm ...

Obtain the popup URL following a fresh request using JavaScript with Playwright

I'm having trouble with a button on my page that opens a popup in a new tab. I have set up a listener to capture the URL of the popup when it opens: page.on('popup', async popup => { console.log('popup => ' + await pop ...

Error with SwitchMap on ActivatedRoute.paramMap

When I try to run the ngOnInit method of my component, I encountered an error with the following line of code. this.products$ = this.route.paramMap.switchMap((params: ParamMap) => this.getProductsForType(params.get('type'))); The error mes ...

Errors can occur when using TypeScript recursive types

Below is a simplified version of the code causing the problem: type Head<T> = T extends [infer U,...unknown[]] ? U : never; type Tail<T> = T extends [unknown,...infer U] ? U : []; type Converter = null; type Convert<T, U extends Converter& ...

The term 'shuterstock_init' is meant to be a type, however, it is mistakenly being treated as a value in this context

I am working on a service called class imageService, which mainly consists of key value pairs export type servicesName = "unsplash" | "pexels" | "pixabay" | 'shutterstock'; export type Service = { [key in services ...

Setting the location of the global nprmrc file on a Windows operating system

Is it possible to change the default global npmrc location in Windows operating systems? ...

Incorporating angular2 with fullpagejs requires loading fullpage js after successfully binding data within Angular

Trying to incorporate fullpage js features into Angular2 has been a challenge for me. The issue arises when I have multiple sections on my page, with one section having child sections generated through JSON data using template binding. For example, the "se ...

Angular: determining if the current route or page is secured by a guard

I am currently working with Angular 9 and I was wondering if there is a way to determine if the current page is protected or guarded during the APP_INITIALIZER phase. Within my APP_INITIALIZER setup, I need to be able to identify whether the route being a ...

The functionality of Flowbite Drawer is disabled when used within an ngFor loop in Angular

Currently, I am utilizing Flowbite () as a Tailwind CSS plugin in my Angular project. Everything is functioning perfectly except for an issue that arises when I try to call a drawer button within a table generated using ngFor. Unfortunately, I am at a los ...

ESLint detecting error with returning values in async arrow functions

Currently facing a minor inconvenience instead of a major problem. Here is the code snippet causing the issue: export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => { const token = getTokenCookie(req) if (!t ...

What is the reason behind the equality comparison between number[][number] and number in TypeScript?

https://i.stack.imgur.com/htnkb.png type Test = number[][]; // The Test type will be inferred as 'number' based on the image above. Can you explain why number[] is considered an index signature type with a signature of 'number'? ...

What is the best way to export a ReactTS component along with its children?

After importing the component, I proceed to declare a new component which will be a child for the invoked one. import { someComponent } from './someComponent'; This is how I export it: const anotherComponent = () => {...}; export { someCompon ...

I must remove the thumb from the input range control

I am looking for a way to remove the thumb from the progress bar in my music player. I have tried various methods without success, and I simply want the progress bar to move forward with color change as it advances based on the Progress variable. For refe ...

Using Arrow Functions in Angular 2 Typescript with Support for IE11

Are arrow functions in Typescript for Angular2 compatible with IE 11? I have come across information stating that arrow functions in javascript may not be supported in IE 11, but I am uncertain if the same applies to Typescript. ...

What is the best way to retrieve the Object key for the connected object in angularFire2?

When I search the database using a user key, I check if an associated object exists: let url = ``/userMember/${userKey}``; const userMemberRef = this.af.database.object(url, { preserveSnapshot: true }); userMemberRef.subscribe(data => { if(data.val ...