2017-09-15 245 views

回答

1

多種方式,都涉及隱藏你的主題,給消費者帶來了包裹觀察到:

想知道當事情訂閱你的主題?

const subject = new Subject(); 
const observable = Observable.defer(() => { 
    someoneJustSubscribed(); 
    return subject; 
}); 
return observable; 

想知道什麼時候有人退訂嗎?

const subject = new Subject(); 
const observable = subject.finally(() => someoneJustUnsubscribed()); 
return observable; 

想知道嗎?

const subject = new Subject(); 
const observable = Observable.create(observer => { 
    someoneJustSubscribed(); 
    const sub = subject.subscribe(observer); 
    return() => { 
     someoneJustUnsubscribed(); 
     sub.unsubscribe(); 
    } 
}); 
return observable;