RxSwift简单的后台任务示例

时间:2017-01-27 08:32:29

标签: swift3 rx-swift

我有一个方法如下

public static func createAlbum(named: String, completion: (album: PHAssetCollection?) -> ()) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {

      }) { success, error in


                completion(album: album)
          }
       }
}

如何使用RxSwift执行后台任务

完整代码

https://gist.github.com/sazzadislam-dsi/d347909d284674c936e397ac423703cf

2 个答案:

答案 0 :(得分:2)

首先,你的函数必须返回一个Observable。

public static func rx_createAlbum(named: String)-> Observable<PHAssetCollection?>

其次,当出现错误时,您的函数将返回onError,当successtrue时,您的函数将返回onNext(album)onCompleted()

代码:

public static func rx_createAlbum(named: String)-> Observable<PHAssetCollection?> {
    return Observable.create { observer in

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {

            // ...

            }) { success, error in

                if error {
                    observer.onError(error)
                }
                else {
                    var album: PHAssetCollection?
                    if success {
                        let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([placeholder?.localIdentifier ?? ""], options: nil)
                        album = collectionFetchResult.firstObject as? PHAssetCollection

                    }

                    observer.onNext(album)
                    observer.onCompleted()
                }

            }
        }

        return Disposables.create()

    }
}

答案 1 :(得分:2)

@XFreire答案是对的,但对于 Swift 3 RxSwift 3.1.0 ,我会在PHAssetCollection添加一个扩展程序:

extension Reactive where Base: PHPhotoLibrary {
    func createAlbum(named name: String) -> Observable<PHAssetCollection?> {
        return Observable.create { observer in
            self.base.performChanges({ 
                // ...
            }, completionHandler: { success, error in
                if success {
                    // Your success logic goes here
                    let album = PHAssetCollection()
                    // ...
                    observer.on(.next(album))
                    observer.on(.completed)
                } else if let error = error {
                    observer.on(.error(error))
                } else {
                    // Your error type
                    observer.on(.error(MyErrors.Unknown))
                }
            })

            return Disposables.create()
        }
    }
}

然后你可以使用这样的方法:

PHPhotoLibrary
    .shared().rx.createAlbum(named: "MyAlbum")
    .subscribe(onNext: { collection in
        // ...
    }, onError: { error in
        // ...
    })
    .addDisposableTo(disposeBag)