source

RxJS에서 관찰 가능한 두 개를 '기다리는' 방법

manysource 2023. 6. 4. 10:37

RxJS에서 관찰 가능한 두 개를 '기다리는' 방법

내 앱에는 다음과 같은 것이 있습니다.

this._personService.getName(id)
      .concat(this._documentService.getDocument())
      .subscribe((response) => {
                  console.log(response)
                  this.showForm()
       });

 //Output: 
 // [getnameResult]
 // [getDocumentResult]

 // I want:
 // [getnameResult][getDocumentResult]

두 결과가 , 첫는 그면나두결얻과는를다, 번로째첫된입니다._personService 그음에다._documentService전화하기 에 두 를 어떻게 요?this.showForm()각 항목의 결과를 처리하는 것입니다.

마지막 업데이트:2022년 3월

RxJS v7: 최신 버전 결합와 함께

반응형 X 설명서에서:

관찰 가능한 입력이 값을 내보낼 때마다 모든 입력의 최신 값을 사용하여 공식을 계산한 다음 해당 공식의 출력을 내보냅니다.

// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();
    
name$.pipe(
        combineLatestWith($document)
      )
      .subscribe(([name, document]) => {
           this.name = name;
           this.document = pair.document;
           this.showForm();
       })

(사용 안 함) RxJS v6 combineLatest()

반응형 X 설명서에서:

관찰 가능한 입력이 값을 내보낼 때마다 모든 입력의 최신 값을 사용하여 공식을 계산한 다음 해당 공식의 출력을 내보냅니다.

(업데이트: 2021년 2월):

// Deprecated (RxJS v6)
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();
    
name$.combineLatest(document$, (name, document) => {name, document})
    .subscribe(pair => {
           this.name = pair.name;
           this.document = pair.document;
           this.showForm();
       })

(대체 구문): combineLatest(관측 가능)

// Deprecated (RxJS v6)
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();
    
combineLatest(name$, document$, (name, document) => ({name, document}))
    .subscribe(pair => {
           this.name = pair.name;
           this.document = pair.document;
           this.showForm();
       })

zip vs combineLatest

(업데이트: 2018년 10월) 이전에 사용을 제안했습니다.zip방법. 일부 그나일사사경우의례용부러▁cases,우경,combineLatest 비해 몇 가지 장점이 .zip따라서 차이점을 이해하는 것이 중요합니다.

CombineLatest관측 가능한 값에서 최근에 방출된 값을 방출합니다.하는 동안에zip메소드는 순차적으로 방출된 항목을 방출합니다.

예를 들어 관측 가능한 #1이 세 번째 항목을 방출하고 관측 가능한 #2가 다섯 번째 항목을 방출했다고 가정합니다.사용한 결과zip방법은 두 가지 모두의 세 번째 방출 값이 됩니다.observables.

이 상황에서 결과는 다음을 사용합니다.combineLatest5일3일이 될 것 같아요.


Observable.zip(관찰 가능)

(원답: 2017년 7월) Observable.zip 메서드는 반응형 X 문서에 설명되어 있습니다.

여러 관측치를 결합하여 각 입력 관측치의 값을 순서대로 계산한 관측치를 만듭니다.

// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();
    
Observable
    .zip(name$, document$, (name: string, document: string) => ({name, document}))
    .subscribe(pair => {
           this.name = pair.name;
           this.document = pair.document;
           this.showForm();
       })

사이드 노트(두 가지 방법 모두에 적용됨)

매개 변수는 함를제마매막개변입니다.(name: string, document: string) => ({name, document})선택 사항입니다.생략하거나 더 복잡한 작업을 수행할 수 있습니다.

최신 파라미터가 함수인 경우 이 함수는 입력 값에서 생성된 값을 계산하는 데 사용됩니다.그렇지 않으면 입력 값의 배열이 반환됩니다.

마지막 부분을 건너뛰면 배열이 나타납니다.

// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();
    
Observable
    .zip(name$, document$)
    .subscribe(pair => {
           this.name = pair['0'];
           this.document = pair['1'];
           this.showForm();
       })

사용하다forkJoin()관측 가능한 방법참조를 위해 이 링크를 확인하십시오.

RXJS 문서에서

이 연산자는 관측치 그룹이 있고 각 관측치의 최종 방출 값에만 관심이 있을 때 가장 잘 사용됩니다.이에 대한 일반적인 사용 사례 중 하나는 페이지 로드(또는 다른 이벤트) 시 여러 요청을 발행하고 모두에 대한 응답이 수신된 경우에만 작업을 수행하려는 경우입니다.이 방법은 Promise를 사용하는 방법과 유사합니다.일체의

forkJoin([character, characterHomeworld]).subscribe(results => {
  // results[0] is our character
  // results[1] is our character homeworld
  results[0].homeworld = results[1];
  this.loadedCharacter = results[0];
});

다음에서 가져온 코드: https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs

Dummies를 위한 RxJS 연산자: forkJoin, zip, combinLatest, withLatestFrom이 저에게 많은 도움이 되었습니다.이름에서 알 수 있듯이 다음과 같은 조합 연산자를 설명합니다.

그 중 하나라도 당신이 찾고 있는 것일 수 있습니다.자세한 내용은 기사를 참조하십시오.

직접 인수 분해를 사용하고 유형을 자동으로 추가하는 Hamid Ashgari 답변 개선(유형 스크립트 사용 시)

const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

combineLatest([name$, document$]).subscribe(([name, document]) => {
    this.name = name;
    this.document = document;
    this.showForm();
});

보너스: 다음과 같이 위의 접근 방식을 사용하여 오류를 처리할 수도 있습니다.

import { combineLatest, of } from 'rxjs';
//...

const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

combineLatest([
  name$.pipe(     catchError( () => of(null as string  ) ) ), 
  document$.pipe( catchError( () => of(null as Document) ) ), // 'Document' is arbitrary type
]).subscribe(([name, document]) => {
    this.name = name;          // or null if error
    this.document = document;  // or null if error
    this.showForm();
});

2021년 6월

rxjs 6.6.7 사용

combineLatest를 이렇게 사용하지 않으면 더 이상 사용하지 않습니다.

combineLatest([a$ , b$]).pipe(
      map(([a, b]) => ({a, b})) //change to [a , b] if you want an array
    )

@nyxz 게시물도 참조

zip - 항상 팀으로 일하는 사랑의 새들은 모든 관찰 가능한 것들이 새로운 값을 반환할 때만 트리거합니다.

combineLatest - 모든 관찰 가능한 값이 새 값을 반환하면 더치를 실행하고 트리거를 시작한 다음 사람이 없을 때까지 기다립니다. 관찰 가능한 값이 새 값을 반환할 때마다 트리거합니다.

withLatestFrom - 마스터 슬레이브는 먼저 슬레이브를 대기하고, 그 후 마스터가 새 값을 반환할 때만 작업이 트리거됩니다.

forkJoin - 최종 대상, 모든 관측 가능한 항목이 완료되면 한 번 트리거합니다.

보낸 사람: https://scotch.io/tutorials/rxjs-operators-for-dummies-forkjoin-zip-combinelatest-withlatestfrom/amp

'combineLatest' 방법을 살펴보십시오. 여기에 적합할 수 있습니다.http://reactivex.io/rxjs/class/es6/Observable.js ~Observable.html#static-method-combineLatest

const { Observable } = Rx

const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

Observable
    .combineLatest(name$, document$, (name, document) => ({ name, document }))
    .first() // or not, implementation detail
    .subscribe(({ name, document }) => {
        // here we have both name and document
        this.showForm()
    })

저에게 이 샘플은 최선의 해결책이었습니다.

const source = Observable.interval(500);
const example = source.sample(Observable.interval(2000));
const subscribe = example.subscribe(val => console.log('sample', val));

따라서 두 번째(예:)가 방출될 때만 첫 번째(소스)의 마지막 방출 값을 볼 수 있습니다.

나의 업무에서, 나는 유효성 확인서와 다른 DOM 이벤트를 기다립니다.

다음과 같이 'zip' 또는 'buffer'를 사용할 수 있습니다.

function getName() {
    return Observable.of('some name').delay(100);
}

function getDocument() {
    return Observable.of('some document').delay(200);
}

// CASE1 : concurrent requests
Observable.zip(getName(), getDocument(), (name, document) => {
    return `${name}-${document}`;
})
    .subscribe(value => console.log(`concurrent: ${value}`));

// CASE2 : sequential requests
getName().concat(getDocument())
    .bufferCount(2)
    .map(values => `${values[0]}-${values[1]}`)
    .subscribe(value => console.log(`sequential: ${value}`));

언급URL : https://stackoverflow.com/questions/44004144/how-to-wait-for-two-observables-in-rxjs