2017-08-12 30 views
2

時,主題會發出一個值如何讓訂閱者在訂閱時發出一個值?當訂閱

let mySubject = new Subject<string> 
// specify somehow that when you subscribe to mySubject, it emits 'foo' 

mySubject.subscribe(value => { 
    // get 'foo' here 
}); 
+3

根據您的使用情況(無法真正從問題推斷出),「BehaviorSubject」 - 作爲初始值 - 或ReplaySubject - 重播指定數量的最新值。 – cartant

+0

這就是答案。 '使用行爲主題'' – Skeptor

回答

0

你只需要數據使用.next

現在推到流下面的代碼應該工作:

const mySubject = new Subject() 

mySubject.subscribe(value => { 
    console.log(value) 
}); 

mySubject.next("foo") 
0

您不僅可以從Subject其實你散發出流/值可以將流/值發送到多個Observers。這意味着你可以附加多個觀察者到Subject。每個Subject可以包含Observer的集合。當你訂閱那個主題時,它會向其集合中的每個觀察者發送流/值。

const subject = new Rx.Subject() 
// add an observer to the list of observers of the subject 
const sub1 = subject.subscribe(function(val){ 
     console.log("observer 1", val); 
}); 
// add another observer to the list of observers of the subject 
const sub2 = subject.subscribe(function(val){ 
     console.log("observer 2", val); 
}); 
// notify all observers in the list with "hi there" 
subject.next('hi there'); 

// remove observer1 from the list 
sub1.unsubscribe(); 

不僅如此,您可以使用Subject作爲Observer並將其提供給Observable。這意味着您可以使用主題將Observable「多播」到多個觀察者。

// To "share" the observable tick$ with two observers, 
// this way, we can pipe all notifications 
// through a Subject, like so 

const tick$ = Rx.Observable.interval(1000); 
const subject = new Rx.Subject(); 
subject.subscribe(function(val){ 
    console.log('from observer 1: '+ val); 
}); 
subject.subscribe(function(val){ 
    console.log('from observer 2: '+ val); 
}); 
tick$.subscribe(subject); 

爲了瞭解RxJs你已經瞭解Observer Pattern通過「Gang Of Four」規定。我會建議你嘗試理解觀察者模式,我希望你能清楚地知道RxJs庫在做什麼。

還有另外一個精彩的reference來自Learning JavaScript Design PatternsAddy Osmani

0

我相信你,你希望有什麼樣的描述實際上是你不希望有什麼..

舉例來說,如果你希望你受到每一個有人訂閱它的時候發出富,那麼你就可以延長學科。

https://jsfiddle.net/v11rndmt/

class MySubject extends Rx.Subject{ 
    constructor(){ super(); } 
    subscribe(oOrOnNext, onError, onCompleted){ 
    const subs = super.subscribe(oOrOnNext, onError, onCompleted); 
    this.next("foo") 
    return subs; 
    } 
} 

let sub = new MySubject() 
sub.subscribe(v => console.log(v)); 
sub.subscribe(v => console.log(v)); 
sub.subscribe(v => console.log(v)); 

這將發射foo的3倍。第一次只有一個用戶,所以它會打印一次。第二次有兩個,所以它會打印兩次。第三個是3,所以它會打印3次。因此foo將被打印6次。

但我沒有搞清楚這個用例。因此,也許你應該提供給我們更多的信息。