[英]Values emitted by RxJS Subject not going through .pipe(...)
在下面的代碼中,我嘗試構建一個 RxJS pipe 並使用pipe
處理主題發出的值。 代碼有效,但結果與我預期的不同。
const rxjs = require("rxjs");
var subject = new rxjs.Subject();
subject
.pipe(rxjs.tap(console.log('tap')))
.subscribe(console.log);
function sendRequest(requestID, cb) {
var delay = Math.floor(Math.random() * (6 - 3 + 1)) + 5;
var request = {
hostname: "httpbin.org",
headers: { "request-id": requestID },
path: "/delay/." + delay,
};
require("http")
.get(request, (res) => {
var body = "";
res.on("data", function (chunk) { body += chunk; });
res.on("end", function () { cb(res, body); });
})
.end();
}
concurrentRequests(5);
function concurrentRequests(limit) {
for (var i = 0; i < limit; i++) {
sendRequest(i, function (res, body) {
var reqID = JSON.parse(body).headers["Request-Id"];
subject.next("Concurrent Response #" + reqID + " returned a " + res.statusCode);
});
}
}
我的目的是構建一個 pipe 來使用來自 RxJS 庫的Subject
處理每個發出的值,當我運行上面的代碼時,我希望得到這個 output:
tap
Concurrent Response #1 returned a 200
tap
Concurrent Response #0 returned a 200
tap
Concurrent Response #2 returned a 200
tap
Concurrent Response #3 returned a 200
tap
Concurrent Response #4 returned a 200
但是 output 是:
tap
Concurrent Response #1 returned a 200
Concurrent Response #0 returned a 200
Concurrent Response #2 returned a 200
Concurrent Response #3 returned a 200
Concurrent Response #4 returned a 200
為什么發出的值沒有通過 pipe?
在
subject.pipe(rxjs.tap(console.log('tap')))
您提供了一個值而不是回調:
subject.pipe(rxjs.tap(() => console.log('tap')))
您執行了console.log('tab')
並將undefined
的值傳遞給rxjs.tap
,而實際上您想添加一個觀察者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.