首页 > Web开发 > 详细

[RxJS] Encapsulate complex imperative logic in a simple observable

时间:2020-04-08 17:57:30      阅读:80      评论:0      收藏:0      [点我收藏+]

Two very important features of the Observable primitive is that they can be activated by subscribing to them and disposed off when we are not interested in them anymore. All good observables need to clean up after themselves when they are disposed off. We took advantage of this when we wrote the observable that switches to showing the loader when the count is positive, and stops listening to it when the count is zero. In this lesson, we will learn how to encapsulate all the complex imperative logic for showing and hiding the spinner, inside a simple observable that can be plugged into any stream.

 

  shouldShowSpinner.pipe(
    switchMap(() => showSpinner.pipe(takeUntil(shouldHideSpinner)))
  )

 

Inside Observable constructor, you can put some side effect code. For example, when ‘showSpinner‘ get triggered, we will show the spinner.

When the ‘showSpinner‘ observable complete, it will call the unsubscribe function we return to hide spinner.

const showSpinner = new Observable(() => {
  const loadingSpinnerPromise = initLoadingSpinner();

  loadingSpinnerPromise.then(spinner => {
    spinner.show()
  })

  return () => {
    loadingSpinnerPromise.then(spinner => {
      spinner.hide();
    })
  }
});

 

[RxJS] Encapsulate complex imperative logic in a simple observable

原文:https://www.cnblogs.com/Answer1215/p/12660529.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!