我對RxJS有點新,它踢我的屁股,所以我希望有人能幫助!爲什麼我的RxJS Observable馬上完成?
我在我的快遞服務器上使用RxJS(5)來處理行爲,我必須保存一堆Document
對象,然後將其中的每個對象發送給他們的收件人。在我documents/create
端點的代碼看起來是這樣的:
// Each element in this stream is an array of `Document` model objects: [<Document>, <Document>, <Document>]
const saveDocs$ = Observable.fromPromise(Document.handleCreateBatch(docs, companyId, userId));
const saveThenEmailDocs$ = saveDocs$
.switchMap((docs) => sendInitialEmails$$(docs, user))
.do(x => {
// Here x is the `Document` model object
debugger;
});
// First saves all the docs, and then begins to email them all.
// The reason we want to save them all first is because, if an email fails,
// we can still ensure that the document is saved
saveThenEmailDocs$
.subscribe(
(doc) => {
// This never hits
},
(err) => {},
() => {
// This hits immediately.. Why though?
}
);
的sendInitialEmails$$
函數返回可觀察到的,看起來像這樣:
sendInitialEmails$$ (docs, fromUser) {
return Rx.Observable.create((observer) => {
// Emails each document to their recepients
docs.forEach((doc) => {
mailer.send({...}, (err) => {
if (err) {
observer.error(err);
} else {
observer.next(doc);
}
});
});
// When all the docs have finished sending, complete the
// stream
observer.complete();
});
});
的問題是,當我訂閱saveThenEmailDocs$
,我next
處理程序是從不稱爲,並直接到complete
。我不知道爲什麼...反過來,如果我從sendInitialEmails$$
中刪除observer.complete()
呼叫,則next
處理程序每次都會被調用,而訂閱中的complete
處理程序從不會被調用。
爲什麼不是預期的行爲next
next
complete
發生,而不是它的一個或另一個...我錯過了什麼?
嗨約翰尼,你有沒有能解決這個問題?我知道我遲到了,但最終你的解決方案呢? –