2016-08-03 141 views
0

我想強制rxjs主題一次只有一個訂戶。 我想算訂閱的數量來執行條件主題<any>捕獲訂閱和取消訂閱方法

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; 
} 

是否有緩存訂閱事件,並適當增加櫃檯 和退訂decrese它的方法嗎?我想其他的clases不知道 發生了什麼後面,這樣一來會被迫對時間只有一個 用戶

+0

只有一個用戶的原因是什麼?從技術上講,如果您在第二次訂閱時發生投擲,那麼它就不是透明的 – paulpdaniels

+0

我有一個全局表單對話框,我想強制執行積極的操作,讓一個用戶使用它,因此某個使用它的人不會兩次訂閱相同的事件。我通過擴展Rxjs主題來解決問題 – Nicu

+0

拋出的目的是確保程序員正確使用api – Nicu

回答

0

一個可能的修復,看起來很乾淨是擴展主題類,並使用這個實現,而不是

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); 
    } 
}