【发布时间】:2020-11-03 04:08:00
【问题描述】:
我正在构建一个记录器对象,它异步获取 IP 地址,然后使用该 IP 地址记录所有值。它必须在实例化时就开始收集日志,但只有在获得 IP 地址后才发出它们;之后它应该会正常发射。
这是我的课:
class LoggerService {
constructor() {
let thisIp;
const getIp = Observable.create(function(observer) {
// doing it with a timeout to emulate bad network
setTimeout(() => {
fetch('https://api.ipify.org?format=json').then(response => response.json()).then(response => {
thisIp = response.ip;
console.log('fetched IP: ', thisIp);
observer.next(response.ip);
observer.complete();
});
}, 5000)
});
// this is where I plan to buffer logs until IP is obtained
this.logStream = new Subject().pipe(buffer(getIp));
// for starters - just log to the console with the IP address
this.logStream.subscribe((value) => console.log(thisIp, value));
}
emit = (message) => this.logStream.next(message);
}
但它不能按我的需要工作;它确实将所有缓冲值作为数组输出,但在获得 IP 后停止发送它们:
const logger = new LoggerService();
setInterval(() => {
logger.emit('Hey ' + Math.random())
}, 1000);
// I get five messages and that's it
即使在缓冲之后,如何让它发出我的值?
【问题讨论】:
-
你看过replaySubject而不是主题吗?听起来您可能正在尝试重新发明一个 replaySubject。
标签: rxjs