[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(); }) } });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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