1

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)
})

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

The second flatMap is still returning the entire users object and not the individual user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.