Halting external observation using switchmap without finishing internal observations

After conducting a thorough search, I couldn't find a similar question to mine, so I apologize if this has been asked before.

In my scenario, I have multiple connected observables working in sequence.

One of the observables, let's call it Observable A, triggers another observable, Observable B, using switchmap.

The interesting thing about Observable B is that it functions as a Behavior Subject, although this detail might not be crucial for the issue at hand.

Observable B doesn't complete its operation; instead, it continuously emits either true or false values.

When Observable B receives a true value, it calls yet another observable, Observable C, through switchmap. This chain keeps going on and on.

What I'm aiming for is when Observable B receives false, it should do nothing (which currently works fine). However, when it receives true, it should trigger Observable C (also functioning correctly). The challenge arises because Observable B never completes, leading to an endless loop. How can I make Observable B complete or unsubscribe from it without interrupting the subsequent chain of events? I want the chain to restart whenever Observable B receives a .next(true) rather than continuing indefinitely.

I tried utilizing 'takeUntil' by passing an observable that triggers upon receiving a true value. However, everything abruptly ended, and my main subscription didn't receive any data (Observable C and beyond did not execute).

Below, you'll find some code snippets with certain logic removed:

private initMap(): Observable<boolean> {
      return this.platformHelperService.getUserLocation().pipe(
        switchMap(_ => {
         return this.updateMapCenterLocation();

public updateMapCenterLocation(): Observable<boolean> {
    let mapCenterSetObserver: Observer<void>;
    const mapCenterSetObservable = Observable.create(
      (observer: Observer<void>) => {
        mapCenterSetObserver = observer;
      }
    );

    // This corresponds to Observable B
    return this.mapAssignedBehaviorSubject.pipe(
        switchMap(assigned => {
        if (assigned) {
          // Observable C implementation below. Additional tasks are performed after completion.
          return this.platformHelperService.getUserLocation()
          // Executing the lines below causes the initial subscription to instantly finish with Observable C failing to run.
          // Omitting these lines leads to Subscription B never reaching completion.
          mapCenterSetObserver.next(undefined);
          mapCenterSetObserver.complete();
        }
   }),
   takeUntil(mapCenterSetObservable)
   );
  }

Answer №1

Allowing truth to flow through once in Observable B could be a viable solution.


ObservableA.pipe(
switchMap(() => ObservableB.pipe(filter(res => res), take(1)),
switchMap(() => ObservableC())
)

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

The npm installation process has come to a sudden halt

Starting a web application in Angular 17 has been my goal. I typically run npm install followed by ng serve. However, this process suddenly stopped working. To troubleshoot, here are the steps I've taken: Updated npm to the latest version (10.2. ...

Showing an error message upon submission in Angular 4 according to the server's response

Struggling for hours to display an error message when a form submits and returns an error status code. The solution seems elusive... In the login form component below, I've indicated where I would like to indicate whether the form is valid or invalid ...

How can you customize the color of the arrows in Carousel Bootstrap?

I've utilized Carousel Bootstrap to create a slideshow, but I'm struggling with changing the color of the arrows. Could you please assist me in figuring out how to change the color of the arrows? Thank you! slideshow.component.html: <di ...

Describe a category of alternating couples

After coming across the query on How to define array with alternating types in TypeScript?, I discovered that it is indeed possible to specify a type of array where the elements must follow a specific order. For instance, the following sequences are consid ...

How can we retrieve and display the value of a property within an object nested in a FormControl within a FormGroup?

Encountering an issue with form control. I have developed a reactive form consisting of 2 controls - an object and a formArray. However, when I bind the "start" control to the HTML, it displays as [Object Object] instead of binding to the address property ...

Scroll to the bottom of the text area or input field - Ionic 3, Angular 2+

Whenever I attempt to use the method provided below, my cursor seems to not move to the end of the textarea as expected. Instead, it appears at the beginning, making editing impossible. How can I find a solution to this issue? HTML <button ion-button ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

Is there a way to align the mat card title and subtitle on a single line?

My code is utilizing Angular material and here is the HTML snippet: <mat-card> <mat-card-header *ngFor="let club of result[0]"> <mat-card-title>{{club.clubName}}</mat-card-title> <mat-card-subtitle>Clu ...

Transform capacitor Camera output into Blob data

I am facing a challenge in converting the output from the Capacitor Camera plugin into a Blob format for uploading to Firebase Storage. Although I could simply upload the Base64 string, I prefer not to alter the existing file upload functionality which ha ...

Is there a way to retrieve the requested data in useEffect when using next.js?

As a newcomer to next.js and TypeScript, I am facing an issue with passing props from data retrieved in useEffect. Despite my attempts, including adding 'return scheduleList' in the function, nothing seems to work. useEffect((): (() => void) = ...

Angular: Custom Pipes Now Adding Currency Symbol to Model Values

I have encountered an issue involving two currency pipe examples. One example involves using the pipe directly in the view, while the other utilizes the pipe from the TypeScript code side. However, when attempting to submit form data, the value related to ...

Exploring nested JSON responses in Angular 2 with TypeScript

Below is the JSON response I received from the REST endpoint: {"image_2_11_0-51-upgrade.iso": {"model": "somemodel", "hostnames": ["abc.com", "abcd,com"], "upload_status": false, "version": "2.11.0-51"}, "image_2_11_0-51-upgrade.iso": {"model": "newmo ...

How to utilize *ngFor alongside the async pipe for conditional rendering in Angular 8 HTML

.html <ng-container *ngFor="let contact of listContact | async; let index = index;"> <h6 class="title" *ngIf="contact && contact['type']"> {{contact['type']}} </h6> <div> {{conta ...

"Exploring the world of Sharepoint Online WebParts with a touch

Recently, I decided to migrate a website that I previously built in SharePoint 2013 to be a Sharepoint Online WebPart. After doing some research, it seems like WebParts are typically created using TypeScript. Is TypeScript really the only way to go about b ...

Can you explain the functionality of `property IN array` in the TypeORM query builder?

I'm looking to filter a list of entity ids using query builder in an efficient way. Here's the code snippet I have: await this._productRepo .createQueryBuilder('Product') .where('Product.id IN (:...ids)', { ids: [1, 2, 3, 4] ...

Any tips on how to personalize the loading animation for single pages using CSS and GIFs?

presentLoading(message) { this.loading = this.loadingCtrl.create({ dismissOnPageChange: false, spinner:'hide', content:`<img class="load" src="assets/dual.gif" />`, }); this.loading.present(); } Hello there! I am working with the ...

"Can you provide tips on how to automatically close a dropdown select menu when the mouse

<div class="row"> <div class="col-sm-6 no-right-border"> <div class="form-group"> <label for="inputFirstName">Filter:</label> <select class="form-control c ...

Various types of generics within an object

Is there a way to achieve different types for the nested K type within a type like MyType? Here's an example: type Config<K> = { value: K; onUpdate: (value: K) => void; } type MyType<F extends string> = { [K in F]: <V>() =& ...

How can I retrieve the selected value from an Angular 2 dropdown menu when it changes, in order to utilize it within a function?

I am currently working on creating a dropdown menu with multiple options. When a user selects an option, I need to make an API call that requires an ID parameter. Inside my component.ts file, I have defined an array containing the values like this: valu ...

Optimal method for efficiently caching data when toggling between list view and detail view within Angular 12

In my Angular App, I have implemented two components - a list view and a details view. Users can switch between these components, both of which utilize multiple async pipes. To minimize the number of http requests to the backend, I decided to cache data u ...