1

I am trying to figure out how to use the result of one observable in another. I have a service call which returns Observable<List<User>> and after that I have another service call where I want to use the id of each user (user.getId()) in the list of the previous observable to create a list of ids List<Int>. Then this list of int will be passed to the second service call. How can I achieve this?

I hope the question makes sense. Let me know if I need to clarify myself.

Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59
chaosmonk
  • 407
  • 6
  • 13

1 Answers1

1

I think you want flatMap. flatMap is an operator, where you can emit another observable based on the item of an Observable.

val obs: Observable<List<User>>
obs.flatMap { users: List<User> -> 
    serviceWhichEmitsObservable.doMagic(users)
}

flatMap-Operator

If you want the users separately, you can convert the Observable> -> Obsersvable with fromIterable. See this answer: RxJava - fetch every item on the list

val obs: Observable<List<User>>
obs
    .flatMap { users: List<User> -> Observable.fromIterable(users)
    .flatMap { user: User -> serviceWhichEmitsObservable.doMagic(user) }

After rereading your question, I think what you want is this: List<User> -> List<Integer> and pass this list to a service. You have to map the list first. This has nothing todo with RX. Nonetheless:

val obs: Observable<List<User>>
obs
    .map { users: List<User> -> users.map { it.id } }
    .flatMap { userIds: List<Integer> -> serviceWhichEmitsObservable.doMagic(userIds) }
morpheus05
  • 4,772
  • 2
  • 32
  • 47
  • Hi, thank you very much. Would this line `obs .map { users: List -> users.map { it.id } } .flatMap { userIds: List -> serviceWhichEmitsObservable.doMagic(userIds) }` return the observable from the second service call – chaosmonk Oct 30 '18 at 10:26
  • Also, I have one more question. Assuming we still have the first service call. But then I just want to use the result (the list of user ids) in a normal method, rather than service call. How would this change? – chaosmonk Oct 30 '18 at 10:28
  • 1
    Yes it would - thats what `flatMap` is here for. `map` maps an item to another item (`List -> List`), `flatMap` allows you return an Observable for a given item (`List -> Observable`). If you want to use the list outside an observable chain you have to `subscribe` to the observable. I would suggest to create a small workspace where you can play around with RX and learn to understand it. – morpheus05 Oct 30 '18 at 10:35
  • On SO its common to accept an answer then rather say "thanks" since thank yous pollute the comments/posts. – morpheus05 Oct 30 '18 at 12:57
  • Is this causing serviceWhichEmitsObservable to execute on different thread or same thread as obs? I feel like it does on a different one - is there a way to force it to execute on same thread – chaosmonk Nov 02 '18 at 18:54