ChatListViewModel.swift 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // ChatListViewModel.swift
  3. // Chat
  4. //
  5. // Created by Sergey Tarasov on 25.07.2022.
  6. //
  7. import Foundation
  8. import XMPPFramework
  9. import XMPPFrameworkSwift
  10. class ChatListViewModel: ObservableObject {
  11. let manager = RosterManager()
  12. @Published var users: [User] = []
  13. var nicknames: [String] {
  14. return users.map({ $0.nickname.isEmpty ? $0.jidString : $0.nickname })
  15. }
  16. var timer: Timer?
  17. init() {
  18. self.timer = Timer.scheduledTimer(
  19. timeInterval: 2,
  20. target: self,
  21. selector: #selector(fetchChatList),
  22. userInfo: nil,
  23. repeats: true
  24. )
  25. }
  26. @objc
  27. public func fetchChatList() {
  28. if users.isEmpty {
  29. let xmppUsers = manager.storage.sortedUsersByAvailabilityName() as? [XMPPUser]
  30. guard let users = xmppUsers?.compactMap({ User(jidString: $0.jid.bare, nickname: $0.nickname) }) else {
  31. return
  32. }
  33. self.users = users
  34. } else {
  35. self.timer?.invalidate()
  36. }
  37. }
  38. }