Nice programing

구독시 마지막으로 관찰 가능

nicepro 2020. 10. 7. 08:18
반응형

구독시 마지막으로 관찰 가능


에 따르면 ,이 기사에 , onCompleteonError의 함수 subscribe상호 배타적이다.

의미 중 하나 onError또는 onComplete이벤트 내에서 실행됩니다 subscribe.
오류를 받거나 정보의 흐름을 성공적으로 마칠 때 실행해야하는 논리 블록이 있습니다.

나는 finallypython 에서 와 같은 것을 찾았지만 내가 찾은 것은 finally내가 만든 관찰 대상에 첨부해야한다는 것뿐입니다.

그러나 나는 구독 할 때만, 그리고 성공적 으로든 오류가 있든 스트림이 종료 된 후에 만 ​​그 논리를하고 싶다.

어떤 아이디어?


이 연산자의 현재 "파이프 가능한"변형이 호출됩니다 finalize()(RxJS 6부터). 오래되고 현재는 사용되지 않는 "패치"연산자가 호출되었습니다 finally()(RxJS 5.5까지).

finalize()연산자가 실제로 맞다고 생각 합니다. 당신은 말한다 :

구독 할 때만 해당 논리를 수행하고 스트림이 종료 된 후에

제 생각에는 문제가되지 않습니다. 원하는 경우 구독하기 전에 싱글 source을 사용하여 사용할 수 있습니다 finalize(). 이렇게하면 항상 다음을 사용할 필요가 없습니다 finalize().

let source = new Observable(observer => {
  observer.next(1);
  observer.error('error message');
  observer.next(3);
  observer.complete();
}).pipe(
  publish(),
);

source.pipe(
  finalize(() => console.log('Finally callback')),
).subscribe(
  value => console.log('#1 Next:', value),
  error => console.log('#1 Error:', error),
  () => console.log('#1 Complete')
);

source.subscribe(
  value => console.log('#2 Next:', value),
  error => console.log('#2 Error:', error),
  () => console.log('#2 Complete')
);

source.connect();

이것은 콘솔에 인쇄됩니다.

#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message

2019 년 1 월 : RxJS 6 업데이트


나를 위해 일한 유일한 것은 이것입니다

fetchData()
  .subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //Called when operation is complete (both success and error)
  });

이제 Angular 응용 프로그램에서 RxJS 5.5.7을 사용 finalize하고 있으며 연산자를 사용하면 성공 또는 오류 콜백 전에 시작되기 때문에 내 사용 사례에 이상한 동작이 있습니다.

간단한 예 :

// Simulate an AJAX callback...
of(null)
  .pipe(
    delay(2000),
    finalize(() => {
      // Do some work after complete...
      console.log('Finalize method executed before "Data available" (or error thrown)');
    })
  )
  .subscribe(
      response => {
        console.log('Data available.');
      },
      err => {
        console.error(err);
      }
  );

I have had to use the add medhod in the subscription to accomplish what I want. Basically a finally callback after the success or error callbacks are done. Like a try..catch..finally block or Promise.finally method.

Simple example:

// Simulate an AJAX callback...
of(null)
  .pipe(
    delay(2000)
  )
  .subscribe(
      response => {
        console.log('Data available.');
      },
      err => {
        console.error(err);
      }
  );
  .add(() => {
    // Do some work after complete...
    console.log('At this point the success or error callbacks has been completed.');
  });

참고URL : https://stackoverflow.com/questions/40707379/observable-finally-on-subscribe

반응형