1

Expected behavior:

1) Get all tasks from taskService.getAllTasks();

2) Pass the result tasks to filterService.addFilterableTasks();

3) Get tasks from filterService.getFilteredTasks();

4) Pass the result tasks to searchService.addTasks();

5) Get tasks from searchService.getBoardFilteredTasks().

this.taskService.getAllTasks().pipe(
          tap((allTasks: Task[]) => {
              this.filterService.addFilterableTasks(allTasks);
              console.log(allTasks) // (1)
          }),
          switchMapTo(this.filterService.getFilteredTasks()),
          tap((tasks: Task[]) => {
              this.searchService.addTasks(tasks);
              console.log(`passed ${tasks.length} tasks`) // (2)
          }),
          switchMapTo(this.searchService.getBoardFilteredTasks()) // (3)
).subscribe((tasks: Task[]) => {          
          /* get the result tasks and show them on a board */
})

Current behavior:

Without line (3):

line 1 => expected array in the console

line 2 => correct number of passed tasks

With line (3):

line 1 and everything further are not triggered. An error says that there are no tasks in searchService.getBoardFilteredTasks

Question:

Is it allowed to use one switchMapTo() after another?

Or is there another way to implement such?

Ivan Burzakovskyi
  • 693
  • 1
  • 8
  • 25

1 Answers1

2

Whenever you're calling switchMapTo(x) it happens long before you subscribe. And x is evaluated right there. Think about it: if I call foo(2 + 1), it will evaluate 2 + 1 to 3 then call foo(3). switchMapTo(this.searchService.getBoardFilteredTasks()) is doing the same thing. So, if something inside of this call to this.searchService.getBoardFilteredTasks() is looking for state that won't be there until the rest of the observable is running, it's going to fail.

You might fix it by using ordinary switchMap which will defer the creation of the observable you're switch-mapping to until a value actually arrives:

switchMap(() => this.searchService.getBoardFilteredTasks())

Generally, if you're calling a function and passing it to switchMapTo, mergeMapTo, etc, you are probably making a mistake. Those are best used with static observable references to avoid confusion,

Ben Lesh
  • 107,825
  • 47
  • 247
  • 232