Reputation: 59395
This is a really entry-level reactive programming question. The following code will log an array of users
from github. How can I get access to loging each individual user.login
using Rx?
import axios from 'axios'
import Rx from 'rx'
let requestStream = Rx.Observable.just('https://api.github.com/users')
let getJSON = (url) => {
return axios.get(url).then(response => response.data)
}
let responseStream = requestStream
.flatMap(function(requestUrl) {
return Rx.Observable.fromPromise(getJSON(requestUrl))
})
responseStream.subscribe(function(response) {
console.log(response)
})
I've tried:
let responseStream = requestStream
.flatMap(function(requestUrl) {
return Rx.Observable.fromPromise(getJSON(requestUrl))
})
.flatMap(user => {
console.log(user)
})
and:
let users = responseStream
.flatMap(user => {
console.log(user)
})
users.subscribe(function(response) {
// console.log(response)
})
Upvotes: 1
Views: 1226
Reputation: 346
To get each individual user from the array, create and return a new observable of that array as follows:
let responseStream = requestStream
.flatMap(function(requestUrl) {
return getJSON(requestUrl);
})
.flatMap(function(usersResponse) {
return rx.Observable.from(usersResponse);
})
.doOnNext(function(user) {
console.log(user);
});
When you call responseStream.subscribe(......)
it should now log each user out individually from the .doOnNext()
method.
I used Mosho's answer as a base for this response with the assumption that the first flatMap returns an array of users from github.
Upvotes: 3
Reputation: 7078
flatMap
handler can return promises, so you don't need fromPromise
.
To get what you need, an observable of the separate items, you can just use flatMap
again, it does exactly what you want. You almost had it right the first try, but the projection (which is merged to a new, returned observable) is what's returned from the flatMap
handler.
import axios from 'axios'
import Rx from 'rx'
let requestStream = Rx.Observable.just('https://api.github.com/users')
let getJSON = (url) => {
return axios.get(url).then(response => response.data)
}
let responseStream = requestStream
.flatMap(function(requestUrl) {
return getJSON(requestUrl);
})
.flatMap(function(x) {
return x;
});
responseStream.subscribe(function(response) {
console.log(response)
})
This way, each element in the array is projected onto a new observable, and they are all merged into a single observable, which is exactly what you want.
Upvotes: 0