2019-07-06 05:06:31 +02:00
|
|
|
//
|
|
|
|
// FetchRequestQueue.swift
|
|
|
|
// NetNewsWire
|
|
|
|
//
|
|
|
|
// Created by Brent Simmons on 6/20/19.
|
|
|
|
// Copyright © 2019 Ranchero Software. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
// Main thread only.
|
|
|
|
|
2019-10-14 07:08:05 +02:00
|
|
|
final class FetchRequestQueue {
|
2019-07-06 05:06:31 +02:00
|
|
|
|
|
|
|
private var pendingRequests = [FetchRequestOperation]()
|
|
|
|
private var currentRequest: FetchRequestOperation? = nil
|
2020-02-18 02:40:40 +01:00
|
|
|
|
|
|
|
var isAnyCurrentRequest: Bool {
|
|
|
|
if let currentRequest = currentRequest {
|
|
|
|
return !currentRequest.isCanceled
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
2019-07-06 05:06:31 +02:00
|
|
|
|
|
|
|
func cancelAllRequests() {
|
|
|
|
precondition(Thread.isMainThread)
|
|
|
|
pendingRequests.forEach { $0.isCanceled = true }
|
|
|
|
currentRequest?.isCanceled = true
|
|
|
|
pendingRequests = [FetchRequestOperation]()
|
|
|
|
}
|
|
|
|
|
|
|
|
func add(_ fetchRequestOperation: FetchRequestOperation) {
|
|
|
|
precondition(Thread.isMainThread)
|
|
|
|
pendingRequests.append(fetchRequestOperation)
|
|
|
|
runNextRequestIfNeeded()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private extension FetchRequestQueue {
|
|
|
|
|
|
|
|
func runNextRequestIfNeeded() {
|
|
|
|
precondition(Thread.isMainThread)
|
|
|
|
removeCanceledAndFinishedRequests()
|
|
|
|
guard currentRequest == nil, let requestToRun = pendingRequests.first else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
currentRequest = requestToRun
|
|
|
|
pendingRequests.removeFirst()
|
2019-10-14 07:19:49 +02:00
|
|
|
currentRequest!.run { (fetchRequestOperation) in
|
2019-07-06 05:06:31 +02:00
|
|
|
precondition(fetchRequestOperation === self.currentRequest)
|
|
|
|
self.currentRequest = nil
|
|
|
|
self.runNextRequestIfNeeded()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func removeCanceledAndFinishedRequests() {
|
|
|
|
pendingRequests = pendingRequests.filter{ !$0.isCanceled && !$0.isFinished }
|
|
|
|
}
|
|
|
|
}
|