[英]Loop with RxSwift
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: 我是Reactive Programming的新手,我有一个我无法独自解决的大问题...我需要按顺序上传几个视频资产,但我不知道该怎么做,我有很多PHAssets,我正在尝试遍历每个元素,并通过网络发送它。到目前为止,这是我的代码并带有注释:
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)
}
If you want to upload your items one by one in flatMap, then use enumeration 如果要在flatMap中一一上传项目,请使用枚举
EDIT: enumeration is useful when you need to know the index of the element, otherwise just flatMap
with one argument will do. 编辑:当您需要知道元素的索引时,枚举很有用,否则仅带一个参数的flatMap
。
Observable.from(items)
.enumerated()
.flatMap() { index, item -> Observable<Item> in
return uploadItem(item)
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
Make observable from collection elements and .flatMap() them to your existing code - 使集合元素中的元素可观察,并将它们.flatMap()变为您现有的代码-
Observable
.from(items)
.flatMap { (item) -> Any in
// your code
return send
}
.subscribe( /* your code */ )
.disposed(by: actionDisposeBag)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.