首页 > 解决方案 > 在离子打字稿中订阅和取消订阅 Observable

问题描述

使用值为 5、15、20 和 30 分钟的无线电列表。默认选择 15 分钟。

现在我需要在选择 5 秒时不断检查功能。when 15 seconds radio button is selected then unsubscribe observable of 5 second and start 15 second subsciber using Observable.

当应用程序处于后台时,我需要不断检查上述场景,选择了哪个单选列表值,并根据我需要启动 Observable 的值。

我正在使用离子框架(下面的代码),何时订阅和取消订阅?

 this.timerOneHourSubscription = Observable.interval(15000)
            .subscribe((val) => { 
      }

下面的例子:

 timerOneHourSubscription: Subscription;
 constructor() {
    this.showBadge();
   }
  }
 /**
 * This function allows to display badge on app icon
 */
showBadge() {
 //by default one hour subscription
 var refreshInterval = 
localStore.getPersistedData(localApp.ISRADIOGROUP_KEY);
 console.log('refreshInterval', refreshInterval);
 this.timerOneHourSubscription = Observable.interval(refreshInterval)
    .subscribe((val) => {
    if (localStore.getPersistedData(localApp.ISRADIOGROUP_KEY) != null) {
        if (localStore.getPersistedData(local.ISBADGE_ENABLED_KEY) != null) {
            let badgeToggleEnable = local.getPersistedData(local.ISBADGE_ENABLED_KEY);
            if (badgeToggleEnable) {
                if (this.Items != null) {
                    if (localStore.getPersistedData(localApp.ITEMS_KEY) != null) {
                        this.Items = localStore.getPersistedData(localApp.ITEMS_KEY);
                        var count = 0;
                        for (let i = 0; i < this.Items.length; i++) {
                        var unRead= this.Items[i].unRead;
                        if (unRead) {
                           count++;
                        }
                        }
                        this.badge.set(unRead++);
                    }
                }
                }
                else {
                    this.badge.clear();
                    }
                }
            }
    });
}

标签: ionic-frameworkionic3observablesubscribe

解决方案


您可以使用以下方式清除您的订阅并调用新订阅。

Observable.interval(15000).takeUntil(this.onDestroy$)
      .subscribe(() => {

当您想要销毁当前订阅并开始新订阅时,这将为您提供帮助。

要销毁当前的,您可以在下面使用:-

this.onDestroy$.next();

您必须在页面顶部声明以下内容:-

private onDestroy$ = new Subject<void>();

不要在 Observable 中发送静态值,而是尝试发送一个方法并一次又一次地调用相同的方法。


推荐阅读