【问题标题】:Loop with RxSwift使用 RxSwift 循环
【发布时间】:2017-11-16 11:07:13
【问题描述】:

我是响应式编程的新手,我有一个无法单独解决的大问题...我需要按顺序上传几个视频资产,但我不知道该怎么做,我有一组PHAssets,我正在尝试遍历每个元素并通过网络发送它 到目前为止,这是我使用 cmets 的代码:

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)

                }

【问题讨论】:

    标签: ios swift reactive-programming rx-swift


    【解决方案1】:

    如果你想在flatMap中一个一个地上传你的物品,那么使用枚举

    编辑:枚举在您需要知道元素的索引时很有用,否则只需 flatMap 和一个参数即可。

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

    【讨论】:

    • 感谢您的出色回复,我有一个问题,我一直在阅读有关 concatMap 的信息,在这种情况下它会有用吗?
    • 顶层的 .concatMap() 保证下游元素的顺序与 items 的顺序相同。自己看是否需要。
    • 我们如何才能等到所有这些都完成?
    【解决方案2】:

    将集合元素和 .flatMap() 变成可观察到您现有的代码 -

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

    【讨论】:

    • 请添加一些解释以避免删除风险
    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2021-12-11
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多