switchMap, startWith, why not try another switchMap?

this.timeline$ = app.selectedSites$.pipe(
  debounceTime(2000),
  switchMap(sites => this.interval.pipe(map(() => sites))),
  switchMap(sites =>
    analytics.timeline(sites, 60 * 24 * 2, 60).pipe(
      map(result => {
        const colors = getColors(result);

        return {
          labels: result[0].datapoints.map(pair => pair[1]),
          datasets: (<any[]>result).map((target, i) => ({
            pointRadius: 0,
            label: target.target,
            fill: false,
            backgroundColor: colors[i % colors.length],
            borderColor: colors[i % colors.length],
            data: target.datapoints.map(pair => ({
              y: pair[0],
              x: pair[1]
            }))
          }))
        };
      })
    )
  ),
  share()
);

How can I modify this.timeline$ to emit null when a new selectedSite is chosen (after debouncing), while loading the first set of data, and then automatically refresh every 30 seconds without emitting null before each refresh? I'm struggling to determine where to include the startWith(null) in this code snippet...

Answer №1

To put it differently - you are looking for two streams: one containing all operators, and another that produces null values.

const source$ = app.selectedSites$
  .pipe(
    debounceTime(2000)
  )


this.timeline$ = source$.pipe(
  switchMap(sites => this.interval.pipe(map(() => sites))),
  switchMap(sites =>
    analytics.timeline(sites, 60 * 24 * 2, 60)
      .pipe(
        map(result => getField(result))
      )
  ),
  merge(source$.pipe(mapTo(null))),
  share()
);

Answer №2

Here's the final result...

convertToChartData(callback: (websites: string[]) => Observable<any>) {
    return this.application.selectedWebsites$.pipe(
      debounceTime(2000),
      switchMap(websites =>
        this.timeInterval.pipe(
          switchMap(() => callback(websites)),
          startWith(null)
        )
      ),
      share()
    );
}

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

Enhance the performance of page loading and implement a consistent spinner feature to ensure smooth transitions for users in Next.js version 13

I am currently working on a project using Next.js 13, and I am encountering issues with slow loading times and an unstable spinner when navigating between pages. Specifically, when transitioning from the home page to the /example page, the experience is n ...

Replacing the '+' character with a space in HttpParams within Angular 6

When passing a JSON object using HttpParams, the + character is automatically converted to a space before being sent to the backend. Despite trying multiple solutions, I have been unable to resolve this issue for a JSONObject string. this.updateUser({"nam ...

Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example: export class Movie { title: string; posterURL: string; description: string; public constructor(cfg: Partial<Movie>) { Object ...

Ways to prevent Deno Workers from using cached source code

Good day, I am currently working on building a custom javascript code execution platform using Deno Workers. Additionally, I have implemented an Oak web server to manage requests for script modifications and their compilation and execution. An issue arise ...

How can TypeORM be used to query a ManyToMany relationship with a string array input in order to locate entities in which all specified strings must be present in the related entity's column?

In my application, I have a User entity that is related to a Profile entity in a OneToOne relationship, and the Profile entity has a ManyToMany relationship with a Category entity. // user.entity.ts @Entity() export class User { @PrimaryGeneratedColumn( ...

Conditional statements in Typescript can be utilized when dealing with unknown data types

In one of my projects, I have a function that executes an asynchronous operation over a collection. I want to add typings to this function for better IDE support - specifically, I want the IDE to infer that the first parameter in the callback function is o ...

Typescript errors in console not being displayed by swc-loader

I have decided to make the switch from ts-loader to swc-loader based on the guidance provided in this article. However, after completing the migration, I am encountering an issue where basic Typescript errors are not being displayed in the console. For ins ...

When using string as a primitive type in Vue 3, what distinguishes the usage of PropType in props from not using it?

The documentation explains how Vue does runtime validation on props with defined types. To enable TypeScript to recognize these types, constructors are cast with PropType. The code example in the documentation uses success: { type: String }, whereas it c ...

Sending chosen selection in a scrollable dropdown menu in Angular

Here is the HTML code that I'm working with: <div class="container"> <div> <h1 class="table-title">Employees</h1> <table class="table"> <thead class="thead-dark"& ...

Vue: Simple ways to retrieve state data in MutationAction

I'm having trouble accessing the state inside @MutationAction Here is the setup I am using: Nuxt.js v2.13.3 "vuex-module-decorators": "^0.17.0" import { Module, VuexModule, MutationAction } from 'vuex-module-decorators' ...

What is the process of type checking in Typescript when passing arguments?

I'm curious about TypeScript and why the two function calls below result in different type checking outcomes. Can someone shed some light on this for me? interface LabelledValue { label: string; } function printLabel(labelledObj: LabelledValue) ...

Issue with Formgroup in Angular Reactive Form - Validation not functioning as expected

I am working with a form group which is defined below: get createItem(): FormGroup { return this.formBuilder.group({ name: ['', Validators.required], email: ['', Validators.required], mobile: ['', V ...

Encountered a WebGL context creation error when running TypeScript tests with Jest

When attempting to initialize WebGLRenderer in one of my Jest test cases, I encounter the following error: Error creating WebGL context. ...

Why is the value not being assigned by the Angular component from the observable service getter?

I am currently working on developing a filter set, and I am facing an issue with the salesChannels array content in my view. The array only gets populated after clicking a button that triggers the test() function. Interestingly, the first time I log the ar ...

angular2 with selenium webdriver: Issue with resolving 'child_process' conflict

I followed these steps: ng new typescript-selenium-example npm install selenium-webdriver --save I also made sure to copy chromedriver to my /Application. I updated the app.component.ts file as shown below: import { Component } from '@angular/core ...

The process of converting an object to a string in Typescript

Currently, I am transforming an Object in Typescript into a string for storage in a database. formData.survey_data = encodeURI(JSON.stringify(formData.survey_data)); The result functions correctly in the browser, however, there is an error being flagged ...

Splitting angular2 and browserify into individual vendor and app bundles can help prevent import errors

I am currently developing an Angular2 application and I am aiming to use gulp and browserify for the build process. By utilizing tsify, I was able to create a standalone bundle.js file, which ended up being 1.4M in size after minification. What I desire ...

The takeUntil function will cancel an effect request if a relevant action has been dispatched before

When a user chooses an order in my scenario: selectOrder(orderId): void { this.store$.dispatch( selectOrder({orderId}) ); } The order UI component triggers an action to load all associated data: private fetchOrderOnSelectOrder(): void { this.sto ...

What is the process for executing a node script within a TypeScript React project?

In my React project, I have incorporated an API for communication. Within the project, there is a module that handles the api access in an abstract manner. This module contains methods like addFoo and getFoos. I need to use this module from a script that ...

Exploring Angular2: Understanding how to retrieve an object with an unknown key

I am trying to showcase a specific value from different objects within a template. The path of the desired value depends on the object being referenced. For example: let obj = { "a": "a", "b": { "1": "1", "2": "READ ME" } } let ...