@@ -79,6 +79,7 @@ final class ChatListViewController: KeyboardObservingViewController {
7979 private var chatDeselectedIndex : IndexPath ?
8080 private var isScrolling = false
8181 private var isRefreshing = false
82+ private var selectedChatRoom : Chatroom ?
8283
8384 let defaultAvatar = UIImage . asset ( named: " avatar-chat-placeholder " ) ?? . init( )
8485
@@ -140,6 +141,10 @@ final class ChatListViewController: KeyboardObservingViewController {
140141 private var loadNewChatTask : Task < ( ) , Never > ?
141142 private var subscriptions = Set < AnyCancellable > ( )
142143 private var swipedIndex : IndexPath ?
144+
145+ // MARK: Subjects
146+ private var unreadBadgeUpdateSubject = ObservableSender < Int ? > ( )
147+
143148 // MARK: Init
144149
145150 init (
@@ -363,6 +368,14 @@ final class ChatListViewController: KeyboardObservingViewController {
363368 self ? . configureCell ( cell, for: chatroom)
364369 }
365370 . store ( in: & subscriptions)
371+
372+ unreadBadgeUpdateSubject
373+ . debounce ( for: . seconds( currentChatBudgeUpdateDelay) , scheduler: DispatchQueue . main)
374+ . sink { [ weak self] count in
375+ guard let self, let count else { return }
376+ self . setBadgeValue ( count)
377+ }
378+ . store ( in: & subscriptions)
366379 }
367380
368381 @MainActor
@@ -615,6 +628,7 @@ extension ChatListViewController: UITableViewDelegate, UITableViewDataSource {
615628 vc. modalPresentationStyle = . overFullScreen
616629 present ( vc, animated: true )
617630 }
631+ self . selectedChatRoom = chatroom
618632 }
619633 }
620634
@@ -785,7 +799,15 @@ extension ChatListViewController: NSFetchedResultsControllerDelegate {
785799 tableView. endUpdates ( )
786800
787801 case let c where c == unreadController:
788- setBadgeValue ( controller. fetchedObjects? . count)
802+ let unreadObjects = controller. fetchedObjects as? [ ChatTransaction ]
803+
804+ if let lastUnread = unreadObjects? . max ( by: { ( $0. sentDate ?? . distantPast) < ( $1. sentDate ?? . distantPast) } ) ,
805+ lastUnread. chatroom == selectedChatRoom {
806+ unreadBadgeUpdateSubject. send ( controller. fetchedObjects? . count)
807+ } else {
808+ unreadBadgeUpdateSubject. send ( nil )
809+ setBadgeValue ( controller. fetchedObjects? . count)
810+ }
789811
790812 default :
791813 break
@@ -1002,6 +1024,7 @@ extension ChatListViewController {
10021024 present ( vc, animated: true )
10031025 }
10041026 }
1027+ selectedChatRoom = chatroom
10051028 }
10061029 private func presentBuyAndSell( ) {
10071030 let buyAndSellVC = screensFactory. makeBuyAndSell ( )
@@ -1669,3 +1692,6 @@ extension UITableView {
16691692 }
16701693 }
16711694}
1695+
1696+ //delay badge update for current chat to not update it if user will read it instantly
1697+ fileprivate let currentChatBudgeUpdateDelay : TimeInterval = 1.0
0 commit comments