[RxJS] Encapsulate complex imperative logic in a simple observable

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();
    })
  }
});
复制代码

 

posted @   Zhentiw  阅读(119)  评论(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-04-08 [Functional Programming] Build a Query function by using Crocks (Pred, Pair, Maybe)
2018-04-08 [Angular] ngx-formly (AKA angular-formly for Angular latest version)
2018-04-08 [React Router] Create a ProtectedRoute Component in React Router (setState callback to force update)
2017-04-08 [SCSS] Organize SCSS into Multiple Files with Partials
2017-04-08 [CSS Flex] Justify-content
2017-04-08 [CSS Flex] Flex direction
2016-04-08 [Git] Automatically running tests before commits with ghooks
点击右上角即可分享
微信分享提示