主题<any>捕获订阅和取消订阅方法

时间:2016-08-03 06:08:44

标签: rxjs rxjs5

我想强制rxjs主题一次只有一个订阅者。 我想计算强制执行条件的订阅数量

 import { Subject } from 'rxjs/Subject';


/**
 * FormDialogActionModel
 */
export class FormDialogActionModel {
    public $customAction: Subject<CustomAction> = new Subject<CustomAction>();

    private positiveActionSubscribers: number = 0;
    private customActionSubscribers: number = 0;
    private $positiveAction: Subject<Object> = new Subject<Object>();    
    private internalToken = 'FORM-DIALOG-SERVICE-GET-POSITIVE-ACTION-WITHOUT-TRIGGERING-GET-RESTRICTIONS';

    /**
     * This get method was created to force the number of subscribers to 1
     */
    public get $$positiveAction(): Subject<Object>  {
        this.positiveActionSubscribers ++;
        if(this.positiveActionSubscribers > 1){
            throw new Error('Somebody already subscribed to a positive action. You cannot subscribe to it again until the subscribes unsubscribes');            
        }

        return this.$positiveAction;    
    }

    public unSubscribePositiveAction(){
        this.positiveActionSubscribers --;
    }

    public getPositiveAction(token){
        if(token != this.internalToken){
            throw new Error('The get mothod getPositiveAction was created only for form-dialog.service');
        }

        return this.$positiveAction;
    }
}

export interface CustomAction {
    data: Object;
    customActionIdentifier: string;
}

有没有办法缓存订阅事件并增加计数器  并取消订阅以减少它?我希望其他的歌词不知道  背后发生了什么,这个被迫只有一个  订户准时

1 个答案:

答案 0 :(得分:0)

  

一个看起来非常干净的可能修复方法是扩展Subject类并改为使用此实现

import { Subject } from 'rxjs/Subject';
import { Observer } from 'rxjs/Observer';
import { Observable } from 'rxjs/Observable';
import { PartialObserver } from 'rxjs/Observer';
import { Subscription } from 'rxjs/Subscription';

export class RxSingleSubject<T> extends Subject<T>{

    constructor(destination?: Observer<T>, source?: Observable<T>) {
        super(destination, source);
    }

    subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void), error?: (error: any) => void, complete?: () => void): Subscription {
        if(this.observers.length == 1){
            throw new Error("RxjsSingleSubject does not support more then one subscriber.");            
        }

        return super.subscribe(observerOrNext, error, complete);
    }
}