Use appDelegate’s coalescing queue for fetching unread counts for smart feeds.

This commit is contained in:
Brent Simmons 2018-02-17 15:15:26 -08:00
parent 9e860321bd
commit 1a5c9d130d
1 changed files with 13 additions and 33 deletions

View File

@ -35,22 +35,26 @@ final class SmartFeed: PseudoFeed {
}
private let delegate: SmartFeedDelegate
private var timer: Timer?
private var unreadCounts = [Account: Int]()
init(delegate: SmartFeedDelegate) {
self.delegate = delegate
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
startTimer() // Fetch unread count at startup
queueFetchUnreadCounts() // Fetch unread count at startup
}
@objc func unreadCountDidChange(_ note: Notification) {
if note.object is Account {
startTimer()
queueFetchUnreadCounts()
}
}
@objc func fetchUnreadCounts() {
AccountManager.shared.accounts.forEach { self.fetchUnreadCount(for: $0) }
}
}
extension SmartFeed: ArticleFetcher {
@ -68,9 +72,12 @@ extension SmartFeed: ArticleFetcher {
private extension SmartFeed {
// MARK: - Unread Counts
func queueFetchUnreadCounts() {
private func fetchUnreadCount(for account: Account) {
appDelegate?.coalescingQueue.add(self, #selector(fetchUnreadCounts))
}
func fetchUnreadCount(for account: Account) {
delegate.fetchUnreadCount(for: account) { (accountUnreadCount) in
self.unreadCounts[account] = accountUnreadCount
@ -78,12 +85,7 @@ private extension SmartFeed {
}
}
private func fetchUnreadCounts() {
AccountManager.shared.accounts.forEach { self.fetchUnreadCount(for: $0) }
}
private func updateUnreadCount() {
func updateUnreadCount() {
unreadCount = AccountManager.shared.accounts.reduce(0) { (result, account) -> Int in
if let oneUnreadCount = unreadCounts[account] {
@ -92,26 +94,4 @@ private extension SmartFeed {
return result
}
}
// MARK: - Timer
func stopTimer() {
if let timer = timer {
timer.rs_invalidateIfValid()
}
timer = nil
}
private static let fetchCoalescingDelay: TimeInterval = 0.1
func startTimer() {
stopTimer()
timer = Timer.scheduledTimer(withTimeInterval: SmartFeed.fetchCoalescingDelay, repeats: false, block: { (timer) in
self.fetchUnreadCounts()
self.stopTimer()
})
}
}