title: RxSwift multiple observable in map
body: <p>I ran into a situation where I would fetch an API which will generate json data of registered users. I would then have to loop through each user and fetch their avatar from remote url and save it to disk. I can perform this second task inside <code>subscribe</code> but this is not a best practice. I am trying to implement it with <code>map</code>, <code>flatMap</code> etc.</p>
  
  <p>Here is my sample code:</p>
  
  <pre><code>self.dataManager.getUsers()
              .observeOn(MainScheduler.instance)
              .subscribeOn(globalScheduler)
              .map{ [unowned self] (data) -&gt; Users in
                  var users = data
  // other code for manipulating users goes here
  // then below I am trying to use another loop to fetch their avatars
  
                  if let cats = users.categories {
                      for cat in cats  {
                          if let profiles = cat.profiles {
                              for profile in profiles {
                                  if let thumbnail = profile.thumbnail,
                                      let url = URL(string: thumbnail) {
                                      URLSession.shared.rx.response(request: URLRequest(url: url))
                                          .subscribeOn(MainScheduler.instance)
                                          .subscribe(onNext: { response in
                                              // Update Image
                                              if let img = UIImage(data: response.data) {
                                                  try? Disk.save(img, to: .caches, as: url.lastPathComponent)
                                              }
                                          }, onError: { (error) in
  
                                          }).disposed(by: self.disposeBag)
                                  }
                              }
                          }
                      }
                  }
  
                  return users
              }
              .subscribe(onSuccess: { [weak self] (users) in
  
              }).disposed(by: disposeBag)
  </code></pre>
  
  <p>There are 2 problems in this code. First is with the <code>rx</code> on <code>URLSession</code> which execute the task in background on another thread and there is no way to acknowledge the main <code>subscribe</code> back when this operation will finish. Second is with the loop and rx which is not efficient as it should generate multiple observables and then process it.</p>
  
  <p>Any idea to improve this logic is welcome.</p>