rxjs "switch to" once the expansion is complete

I am currently working on the following code snippet:

const outputFile = fs.createWriteStream(outputPath);
const requisitionData = this.login().pipe(
  map(response => response.data.token),
  switchMap(loginToken =>
    this.getRequisitions(loginToken).pipe(
      expand(response => {
        const nextPage = response.data.content.meta.cursor.next;
        console.log('Next Page: ' + nextPage);

        return nextPage
          ? this.getRequisitions(loginToken, nextPage ?? undefined)
          : EMPTY;
      }),
      map(response => response.data),
      map(requisitions => this.processRequisitions(requisitions, outputFile)),
    ),
  ),
);

requisitionData.subscribe();

The functionality of this code is as follows:

  • It makes a call to a login endpoint and retrieves the token string
  • Using the token string, it calls a "get requisitions" endpoint
  • It iterates through the paginated results and calls the subsequent page(s)
  • For each page, it saves the result into a file

I want to enhance this code by executing a function once all pages have been traversed, adding a console.log('Process finished');.

However, my attempts to achieve this (such as adding tap(() => console.log()) in different places) lead to multiple executions.

UPDATE:

I successfully implemented this by modifying the subscribe() method and passing the callback as the third parameter:

requisitionData.subscribe(
  undefined,
  undefined,
  () => console.log(`Process Finished: Output file: ${outputFile.path}`),
);

Although I still ponder how I can accomplish this within the pipe itself.

Answer №1

To trigger a specific action only when the process is completed, you can provide an Observer to the tap method:

tap({ complete: () => console.log('Process Finished') })

Answer №2

Completing the series requires you to use EMPTY. If you want to proceed to the map operator, you must return something other than of(null).

return nextPage ? this.fetchRequests(loginToken, nextPage ?? undefined) : of(null)

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

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

Mastering the art of typing a member of an abstract generic class in Typescript with consideration for potential additional implementations

It's quite challenging to put into words, but essentially I aim to create a base abstract class outlining an abstract interface that must vary based on whether a derived class implements a specific interface or not. Here is a TypeScript playground de ...

Angular 2, the change event is not triggering when a bootstrap checkbox is clicked

Encountering an issue, the (change) function is not triggering in a specific checkbox. <input [(ngModel)]="driver.glasses" name="glasses" type="checkbox" class="make-switch" (change)="changeFunction()" data-on-color="primary" data-off-color="info"&g ...

Testing the creation of elements dynamically with jestLooking into jest for dynamically adding

Attempting to test a dynamic element using TypeScript, but struggling to understand the process. Can anyone offer guidance? Below is the TypeScript file: export default class MyClass { constructor(){ this.render(); } render() { ...

Ways to sequentially execute API calls rather than concurrently

Update: Find the complete solution at the end of this answer. Consider the following code snippet: @Injectable() export class FileUploader { constructor(private http: Http) {} upload(url: string, file: File) { let fileReader: FileReader ...

Utilizing Angular 2 for a dynamic Google Map experience with numerous markers

I am currently working on an Angular2 project that involves integrating Google Maps. My goal is to display multiple markers around a specific area on the map. Although I have been able to get the map running, I am facing issues with displaying the markers ...

Tips for properly waiting for an AngularFire2 subscription to complete before executing the subsequent lines of code within Angular2

Having an issue with my Angular2 Type Script code. The goal is to access Questions from a Firebase Database by subscribing to a FirebaseListObserver: this.af.list('/questions').subscribe( val => { this.questions = val console.log(th ...

Tips for adjusting the position of nodes that are overlapping in React Flow

Whenever node1 is moved over node2 in react-flow, they end up overlapping. I am looking to shift node2 towards the right to avoid this overlap. The desired outcome is for node2 to be shifted to the right side. ...

Struggling to grasp how to implement Redux and React-router together in one component

I have recently embarked on learning TypeScript and encountered a confusing behavior. Upon encountering this error: Type 'ComponentClass<{}>' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

Is it possible to enhance the GamepadAPI's functionality?

I've been working on enhancing the built-in GamepadAPI by adding custom controller code. With TypeScript, I created a basic function to trigger a "gamepadconnected" event. // emulate gamepadconnected event function dispatchGamepadConnectedEv ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

Experience a captivating Angular slideshow carousel that resets when you click on a dot button, all powered by the magical capabilities of

Check out this Stackblitz Link for a working sample. I have developed an angular carousel slider component using rxjs. Each slide changes after 5 seconds and everything is working smoothly. However, I am facing an issue where clicking on a particular dot ...

What could be the reason my RxJS Observable chain does not run again when new emissions are made?

Currently, I am facing a unique challenge while working with RxJS in an Angular service. The issue revolves around two observable chains designed to enhance a stream of notifications with user data. One chain functions correctly, allowing for multiple trig ...

Using the Amazon Resource Name (ARN) of a Cloud Development Kit (CDK) resource in a different

Having trouble obtaining the ARN of my AWS CDK stack's Step Functions state machine for my lambda function. The ARN is constantly changing and I'm unsure how to access it. I attempted to create a .env file alongside the lambda function's in ...

Unlock the Power of EmailJS with Vue.js 2 and TypeScript

I couldn't find a similar issue online, so here's my problem. I'm trying to create a form for receiving contact from an app using Vue.js 2 and TypeScript. Here is my code: <form ref="form" class="form-data" @submit.pr ...

Hiding the line connector between data points in ChartJs

I recently took over a project that includes a line chart created using Chart.js by the previous developer. My client has requested that I do not display a line between the last two data points. Is this possible with Chart.js? I have looked through the doc ...

Angular is notifying that an unused expression was found where it was expecting an assignment or function call

Currently, I am working on creating a registration form in Angular. My goal is to verify if the User's username exists and then assign that value to the object if it is not null. loadData(data: User) { data.username && (this.registrationD ...

Prevent the function from affecting type deduction

I am working with a type similar to this: interface Test<R, T> { inputType: R; transformer: (input: R extends any ? R : never) => T; } // function for inferring type function inferTest<T extends Test<any, any>>(t: T): T { ...

Sending information to components in Angular using Router

Should I pass data through the angular router to a component, or is it better to use a service? Currently, the component is receiving data in the following way: this.account = activatedRoute.snapshot.data.account ...