Skip to content

Instantly share code, notes, and snippets.

@RuiAAPeres
Last active November 12, 2015 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RuiAAPeres/e9077be58e7359259a01 to your computer and use it in GitHub Desktop.
Save RuiAAPeres/e9077be58e7359259a01 to your computer and use it in GitHub Desktop.
import Foundation
import ReactiveCocoa
final class PriorityAction<T> {
let identifier : String
let action : Action<Void, [T], Error>
init(identifier: String, action: Action<Void, [T], Error>) {
self.identifier = identifier
self.action = action
}
}
final class PriorityEngine<T> {
private var queue: [PriorityAction<T>] = []
private var inProgress : Bool = false
func addActionWithPriority(action: PriorityAction<T>) {
queue.enumerate()
.filter{ $0.element.identifier == action.identifier }
.first
.apply { self.queue.removeAtIndex($0.index) }
queue.insert(action, atIndex: 0)
}
func addAction(action: PriorityAction<T>) {
queue.append(action)
}
func start() {
guard self.queue.count > 0 && inProgress == false else { return }
inProgress = true
let action = self.queue.removeFirst().action
action
.apply()
.startOn(QueueScheduler(name: "PriorityEngine.Scheduler"))
.materialize()
.startWithNext(handleEvent)
}
private func handleEvent(event: Event<[T], ActionError<Error>>) {
switch event {
case .Next(_): break
default:
inProgress = false
start()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment