RxJS Toàn Tập (P3 Combination Operator RxJS – forkJoin)

Combination Operator RxJS: forkJoin

Ở phần này, chúng ta sẽ tìm hiểu về các toán tử kết hợp trong RxJS bao gồm: forkJoin, combineAllcombineLatestconcatconcatAllmergemergeAllracezip.Các toán tử này được sử dụng khi nào.

forkJoin

Khi tất cả các observable hoàn thành, phát ra giá trị phát ra cuối cùng của mổi observable Toán tử này được sử dụng tốt nhất khi các bạn có 1 nhóm observable và chỉ quan tâm đến giá trị phát ra cuối cùng của mổi cái. Một trường hợp phổ biến được sử dụng là nếu bạn muốn đưa ra nhiều yêu cầu khi tải trang (hoặc 1 số sự kiện khác), và chỉ muốn hành động tiếp theo khi nhận được phản hồi cho tất cả, trường hợp này giống sử dụng Promise.all Cần nhận thức rằng, bất kỳ observable bên trong cung cấp lỗi cho forkJoin, thì bạn sẽ bị mất giá trị của các observable đã hoàn thành nếu bạn không sử dụng “catch” để bắt lỗi đúng observable bên trong. Nếu bạn chỉ quan tâm đến việc tất cả các observable bên trong thành công, bạn có thể bắt lỗi ở bên ngoài.

Ví dụ:

Ví dụ 1: các observable hoàn thành sau mổi khoảng thời gian khác nhau
// RxJS v6+
import { delay, take } from 'rxjs/operators';
import { forkJoin, of, interval } from 'rxjs';

const myPromise = val =>
  new Promise(resolve =>
    setTimeout(() => resolve(`Promise Resolved: ${val}`), 5000)
  );

/*
  when all observables complete, give the last
  emitted value from each as an array
*/
const example = forkJoin(
  //emit 'Hello' immediately
  of('Hello'),
  //emit 'World' after 1 second
  of('World').pipe(delay(1000)),
  //emit 0 after 1 second
  interval(1000).pipe(take(1)),
  //emit 0...1 in 1 second interval
  interval(1000).pipe(take(2)),
  //promise that resolves to 'Promise Resolved' after 5 seconds
  myPromise('RESULT')
);
//output: ["Hello", "World", 0, 1, "Promise Resolved: RESULT"]
const subscribe = example.subscribe(val => console.log(val));
Ví dụ 2: Xử lý lỗi bên ngoài
// RxJS v6+
import { delay, catchError } from 'rxjs/operators';
import { forkJoin, of, throwError } from 'rxjs';

/*
  when all observables complete, give the last
  emitted value from each as an array
*/
const example = forkJoin(
  //emit 'Hello' immediately
  of('Hello'),
  //emit 'World' after 1 second
  of('World').pipe(delay(1000)),
  // throw error
  throwError('This will error')
).pipe(catchError(error => of(error)));
//output: 'This will Error'
const subscribe = example.subscribe(val => console.log(val));
Ví dụ 3: Nhận kết quả thành công, khi một lỗi bên trong có thể quan sát được.
// RxJS v6+
import { delay, catchError } from 'rxjs/operators';
import { forkJoin, of, throwError } from 'rxjs';

/*
  when all observables complete, give the last
  emitted value from each as an array
*/
const example = forkJoin(
  //emit 'Hello' immediately
  of('Hello'),
  //emit 'World' after 1 second
  of('World').pipe(delay(1000)),
  // throw error
throwError('This will error').pipe(catchError(error => of(error)))
);
//output: ["Hello", "World", "This will error"]
const subscribe = example.subscribe(val => console.log(val));
Ví dụ 5: forkJoin trong Angular
@Injectable()
export class MyService {
  makeRequest(value: string, delayDuration: number) {
    // simulate http request
    return of(`Complete: ${value}`).pipe(
      delay(delayDuration)
    );
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>forkJoin Example</h2>
      <ul>
        <li> {{propOne}} </li>
        <li> {{propTwo}} </li>
        <li> {{propThree}} </li>
      </ul>
    </div>
  `,
})
export class App {
  public propOne: string;
  public propTwo: string;
  public propThree: string;
  constructor(private _myService: MyService) {}

  ngOnInit() {
    // simulate 3 requests with different delays
    forkJoin(
      this._myService.makeRequest('Request One', 2000),
      this._myService.makeRequest('Request Two', 1000),
      this._myService.makeRequest('Request Three', 3000)
    )
    .subscribe(([res1, res2, res3]) => {
      this.propOne = res1;
      this.propTwo = res2;
      this.propThree = res3;
    });
  }
}
Nguồn: https://www.learnrxjs.io/operators/combination/forkjoin.html
Rate this post

You May Also Like

About the Author: truongluu

Leave a Reply

Your email address will not be published. Required fields are marked *