Last active
November 12, 2015 18:18
-
-
Save RuiAAPeres/e9077be58e7359259a01 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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