简体   繁体   English

RxJS - Subscriber如何与Observable和Subscription不同?

[英]RxJS - How Subscriber is different from Observable and Subscription?

I have been trying to find an example of wrapping Observable into a Subscriber to monitor async call's status eg loading, completed or errored. 我一直试图找到一个将Observable包装到订阅服务器中的示例,以监视异步调用的状态,例如加载,完成或错误。 Can you provide a short example? 你能提供一个简短的例子吗?

Not sure if this is what you mean, but you can wrap an async http call like so 不确定这是不是你的意思,但你可以像这样包装异步http调用

const httpStream = Observable.create(observer => {

    fetch('http://server.com')
      .then(response => response.json()) 
      .then(data => {
        observer.next(data); // if http call provides progress as well as completion
                             // these can all be pushed with observer.next()
        observer.complete();
      })
      .catch(err => observer.error(err));

  });

  httpStream.subscribe(data => console.log(data));

Of course if it was actually fetch you wanted to wrap you could instead just do 当然,如果它实际上是你想要包装你可以反而只是做

var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));

EDIT: If you are using the angular HttpClient then there is no need to wrap it as it is already an observable. 编辑:如果你正在使用角度HttpClient,那么就不需要包装它,因为它已经是一个可观察的。 To get progress updates as well as the final response something like the following should work 要获得进度更新以及最终响应,以下内容应该有效

const req = new HttpRequest('POST', 'http://api.server.com', body, {
    reportProgress: true
});

this._http.request(req)
.filter((event) => event.type === HttpEventType.UploadProgress || event instanceof HttpResponse)
.map((event) => {
    if (event.type === HttpEventType.UploadProgress) {
        const percentDone = Math.round(100 * event.loaded / event.total);
        return { type: 'uploadProgress', percentDone };
    } else if (event instanceof HttpResponse) {
        return { type: 'httpResponse', status: event.status };
    } 
})
.subscribe((response) => {
    if (response.type === 'uploadProgress') {
        console.log(`upload still in progress - percent done = ${response.percentDone}%`);
    } else {
        console.log(`upload completed  - status = ${response.status}`);
    }
});

If in fact all you want to know is when all the request have completed, and don't need the progress updates from each then rather than pushing the requests into an array a better option might be to use a forkJoin - which is similar to a promise.all in that you only get an output from the observable once all of the sub observables have completed - https://www.learnrxjs.io/operators/combination/forkjoin.html 事实上,如果您想知道所有请求都已完成,并且不需要每个请求的进度更新,而不是将请求推送到数组中,则更好的选择可能是使用forkJoin - 类似于promise.all,一旦所有子可观察量都已完成,你只能从observable得到一个输出 - https://www.learnrxjs.io/operators/combination/forkjoin.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM