1
votes

I'm new to Reactive Programming and I have a big problem that I can't solve alone... I need to upload several video assets and in a orderly sequence but I do not know how to do it, I have an array of PHAssets and I'm trying to iterate thru each element and send it over the network Here is my code so far with comments:

for item in items {
                    let fileName = item.media.localIdentifier

                    //Observable to generate local url to be used to save the compressed video
                    let compressedVideoOutputUrl = videoHelper.getDocumentsURL().appendingPathComponent(fileName)

                    //Observable to generate a thumbnail image for the video
                    let thumbnailObservable =  videoHelper.getBase64Thumbnail(myItem: item)

                    //Observable to request the video from the iPhone library
                    let videoObservable = videoHelper.requestVideo(myItem: item)

                        //Compress the video and save it on the previously generated local url
                        .flatMap { videoHelper.compressVideo(inputURL: $0, outputURL: compressedVideoOutputUrl) }
                    //Generate the thumbnail and share the video to send over the network
                    let send = videoObservable.flatMap { _ in thumbnailObservable }
                        .flatMap { api.uploadSharedFiles(item, filename: fileName, base64String: $0) }

                    //subscribe the observable
                    send.subscribe(onNext: { data in
                        print("- Done chain sharing Video -")
                    },
                                   onError: { error in
                                    print("Error sharing Video-> \(error.localizedDescription)")
                    }).disposed(by: actionDisposeBag)

                }
2

2 Answers

7
votes

If you want to upload your items one by one in flatMap, then use enumeration

EDIT: enumeration is useful when you need to know the index of the element, otherwise just flatMap with one argument will do.

Observable.from(items)
    .enumerated()
    .flatMap() { index, item -> Observable<Item> in
        return uploadItem(item)
    }
    .subscribe(onNext: { print($0) })
    .disposed(by: disposeBag)
2
votes

Make observable from collection elements and .flatMap() them to your existing code -

Observable
  .from(items)
  .flatMap { (item) -> Any in
    // your code
      return send
  }
  .subscribe( /* your code */ )
  .disposed(by: actionDisposeBag)