[Reactive Programming] Async requests and responses in RxJS
2024-10-15 06:26:46
We will learn how to perform network requests to a backend using RxJS Observables.
A example of basic jquery request:
console.clear();
var requestStream = Rx.Observable.just('https://api.github.com/users'); //Current requestStream is just a stream
//We need to subscribe it to make it work
requestStream.subscribe(url => { //Preform a serve reqest by jQuery
jQuery.getJSON(url).done( res => {
console.log(res);
})
});
But it not make so many sence we use jQuery to handle the promise since we already using RxJS:
console.clear();
var requestStream = Rx.Observable.just('https://api.github.com/users'); //Current requestStream is just a stream
//We need to subscribe it to make it work
requestStream.subscribe( url => { //Using Rx.Observable.fromPromise() to handle the response
//Since jQuery.getJSON(url) return a promise
//there we put into the fromPromise() function
var responseStream = Rx.Observable.fromPromise(jQuery.getJSON(url)); //Then subscribe the responseStream
responseStream.subscribe( res => {
console.log(res);
});
});
We see that we can accomplish with promise we also can do in Observable. And the main problem for promise is that promise only even yield a single value. But observalbe can have mult events.
But soon we find we subscribe an stream inside another subscribe, this is what we don't have to do, normal way to avoid this is using flatMap().
Here we do flagMap() but not map() is because inside map() a observable and return another observable then we got an observable of observable.
console.clear();
var requestStream = Rx.Observable.just('https://api.github.com/users');
var responseStream = requestStream
.flatMap( url => Rx.Observable.fromPromise(jQuery.getJSON(url))); responseStream.subscribe( res => console.log(res));
Now we have only one subscribe.
最新文章
- Selenium-java-web常用操作---2
- $.ajax()方法详解
- 。。。contentType与pageEncoding的区别。。。
- attr-img-src
- hdu 3948 Portal (kusral+离线)
- js中settimeout方法加参数
- R语言数据分析
- C#开发Linux守护进程
- LeetCode:60. Permutation Sequence,n全排列的第k个子列
- 分布式事务之如何基于RocketMQ的事务消息特性实现分布式系统的最终一致性?
- 优秀后端架构师必会知识:史上最全MySQL大表优化方案总结
- numpy.loadtxt()
- NLP里面的一些基本概念
- Vue(二)vue-devtools插件
- 微软Power BI 每月功能更新系列——5月Power BI 新功能学习
- Java多态面试题案例几解题思路
- Python之路(第二十五篇) 面向对象初级:反射、内置方法
- python测试开发django-11.模型models详解
- android 自定义照相机Camera黑屏 (转至 http://blog.csdn.net/chuchu521/article/details/8089058)
- IOS #ifdef 的那些事儿