[RxJS] Reactive pattern: Passing Observable and trigger side effect until it complete

For example, we want to show loading spinner inside our appliction component trees. Because we might trigger loading spinner anywhere inside our application, therefore, we need to use a loading.service.ts to communciate between different compnents.

loading.service.ts:

复制代码
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {concatMap, finalize, tap} from 'rxjs/operators';

@Injectable()
export class LoadingService {

  private loadingSubject = new BehaviorSubject<boolean>(false);

  loading$: Observable<boolean> = this.loadingSubject.asObservable();

  loadingOn() {
    this.loadingSubject.next(true);
  }

  loadingOff() {
    this.loadingSubject.next(false);
  }

  showLoaderUntilCompleted<T>(obs$: Observable<T>): Observable<T> {
    return of(null)
      .pipe(
        tap(() => this.loadingSubject.next(true)),
        concatMap(() => obs$),
        finalize(() => {
          this.loadingSubject.next(false);
        })
      );
  }
}
复制代码

Component:

复制代码
import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs';
import {LoadingService} from './loading.service';

@Component({
  selector: 'loading',
  template: '<div class="spinner-container" *ngIf="loading$ | async"><mat-spinner></mat-spinner></div>'
})
export class LoadingComponent implements OnInit {

  loading$ : Observable<boolean>;
  constructor(private loadingService: LoadingService) {

  }

  ngOnInit() {

    this.loading$ = this.loadingService.loading$;
  }
}
复制代码

 

The most important thing to understand here is the function: showLoaderUntilComplete(obs$). 

It takes a Observable, because we want to wait 'obs$' to complete, therefore, we use 'concatMap', it executes observable one by one, then we use 'finalize' operator, it will execute callback function when the observable completes. Here means waiting 'obs$' to be completed.

 

How to use it?

courses.service.ts

复制代码
private subject = new BehaviorSubject<Course[]>([]);

courses$ = this.subject.asObservable();  

private loadAllCourses() {

      const loadCourses$ =  this.http.get<Course[]>('/api/courses')
        .pipe(
          map(response => response["payload"])
        );

      this.loading.showLoaderUntilCompleted(loadCourses$)
        .subscribe(
          courses => this.subject.next(courses)
        );
  }
复制代码

 

posted @   Zhentiw  阅读(414)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-03-07 [Algorithm] Serialize and Deserialize Binary Tree
2018-03-07 [HTML5] a tag, rel="noopener"
2017-03-07 [React] Recompose: Override Styles & Elements Types in React
2017-03-07 [Postgres] Filter Data in a Postgres Table with Query Statements
2017-03-07 [Postgre] Insert Data into Postgre Tables
2017-03-07 [Ramda] Convert Object Methods into Composable Functions with Ramda
2017-03-07 [Django] The admin interface
点击右上角即可分享
微信分享提示