Skip to content

Commit

Permalink
feat: observe unread count to disable filtering when reaching zero
Browse files Browse the repository at this point in the history
  • Loading branch information
adrien-coye committed Jun 8, 2023
1 parent 5587a4a commit 8b8ea1b
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 8 deletions.
44 changes: 36 additions & 8 deletions Mail/Views/Thread List/ThreadListViewModel+Observation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,11 @@ import RealmSwift
import SwiftUI

extension ThreadListViewModel {
// MARK: - Observe global changes

func observeChanges(animateInitialThreadChanges: Bool = false) {
stopObserveChanges()


private func threadResults() -> Results<Thread>? {
guard let folder = folder.thaw() else {
sections = []
return
return nil
}

let threadResults: Results<Thread>
Expand All @@ -39,8 +36,16 @@ extension ThreadListViewModel {
} else {
threadResults = folder.threads.sorted(by: \.date, ascending: false)
}

return threadResults
}

// MARK: - Observe global changes

observationThreadToken = threadResults.observe(on: observeQueue) { [weak self] changes in
func observeChanges(animateInitialThreadChanges: Bool = false) {
stopObserveChanges()

observationThreadToken = threadResults()?.observe(on: observeQueue) { [weak self] changes in
guard let self = self else {
return
}
Expand Down Expand Up @@ -99,7 +104,30 @@ extension ThreadListViewModel {

// MARK: - Observe unread count

/// Observe the unread count to disable filtering when it reaches 0
func observeUnreadCount() {
// TODO observe the unread count to disable filtering when it reaches 0
stopObserveUnread()

observationUnreadToken = threadResults()?.observe(on: observeQueue) { [weak self] changes in
guard let self = self else {
return
}

switch changes {
case .initial(let changes), .update(let changes, _, _, _):
let count = changes.where { $0.unseenMessages > 0 }.count
Task {
await MainActor.run {
self.unreadCount = count
}
}
case .error:
break
}
}
}

func stopObserveUnread() {
observationUnreadToken?.invalidate()
}
}
10 changes: 10 additions & 0 deletions Mail/Views/Thread List/ThreadListViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,15 @@ final class DateSection: Identifiable {
var observationLastUpdateToken: NotificationToken?
let observeQueue = DispatchQueue(label: "com.infomaniak.thread-results", qos: .userInteractive)

@Published var unreadCount: Int = 0 {
didSet {
// Disable filter if we have no unread emails left
if unreadCount == 0 && filterUnreadOn {
filterUnreadOn = false
}
}
}

@Published var filter = Filter.all {
didSet {
Task {
Expand Down Expand Up @@ -165,6 +174,7 @@ final class DateSection: Identifiable {
lastUpdate = folder.lastUpdate
self.isCompact = isCompact
observeChanges()
observeUnreadCount()
}

func fetchThreads() async {
Expand Down

0 comments on commit 8b8ea1b

Please sign in to comment.