0001 // 0002 // OperationQueueScheduler.swift 0003 // Rx 0004 // 0005 // Created by Krunoslav Zaher on 4/4/15. 0006 // Copyright © 2015 Krunoslav Zaher. All rights reserved. 0007 // 0008 0009 import Foundation 0010 0011 /** 0012 Abstracts the work that needs to be performed on a specific `NSOperationQueue`. 0013 0014 This scheduler is suitable for cases when there is some bigger chunk of work that needs to be performed in background and you want to fine tune concurrent processing using `maxConcurrentOperationCount`. 0015 */ 0016 public class OperationQueueScheduler: ImmediateSchedulerType { 0017 public let operationQueue: NSOperationQueue 0018 0019 /** 0020 Constructs new instance of `OperationQueueScheduler` that performs work on `operationQueue`. 0021 0022 - parameter operationQueue: Operation queue targeted to perform work on. 0023 */ 0024 public init(operationQueue: NSOperationQueue) { 0025 self.operationQueue = operationQueue 0026 } 0027 0028 /** 0029 Schedules an action to be executed recursively. 0030 0031 - parameter state: State passed to the action to be executed. 0032 - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. 0033 - returns: The disposable object used to cancel the scheduled action (best effort). 0034 */ 0035 public func schedule<StateType>(state: StateType, action: (StateType) -> Disposable) -> Disposable { 0036 0037 let compositeDisposable = CompositeDisposable() 0038 0039 weak var compositeDisposableWeak = compositeDisposable 0040 0041 let operation = NSBlockOperation { 0042 if compositeDisposableWeak?.disposed ?? false { 0043 return 0044 } 0045 0046 let disposable = action(state) 0047 compositeDisposableWeak?.addDisposable(disposable) 0048 } 0049 0050 self.operationQueue.addOperation(operation) 0051 0052 compositeDisposable.addDisposable(AnonymousDisposable { 0053 operation.cancel() 0054 }) 0055 0056 return compositeDisposable 0057 } 0058 0059 }
OperationQueueScheduler.swift:25 self.operationQueue = operationQueueOperationQueueScheduler.swift:50 self.operationQueue.addOperation(operation)