I have a variable within my @StateObject that is used to show new message notifications. It is updated periodically from my backend (push noti).
The problem is that once this variable updates the badge, it will pull the user out of other tabs unexpectedly (i.e. reloads the entire TabView and takes them to the first tab). I want the notification badge to update without interfering with what the user is doing. I've tried using equatable(), but to no avail. It seems that TabView reloads everything on state object changes. Is there a way to only reload the tab labels? any help will be appreciated.
ContentView.swift:
struct ContentView: View {
@State var tab: UInt = 0
@StateObject var messenger: MessagingViewModel = MessagingViewModel()
@State var firstAppear = true
init() {
UITabBar.appearance().backgroundColor = UIColor(Color.white)
}
var body: some View {
TabView(selection: $tab) {
HomeMarket(tab: $tab)
.tabItem {
Label("Market", systemImage: "house.fill")
}.tag(0)
AddItems(tab: $tab)
.tabItem {
Label("Add Item", systemImage: "plus.circle")
}.tag(1)
MessageList(tab: $tab)
.tabItem {
Label("Messages", systemImage: "envelope.fill")
}
.tag(2)
.badge(messenger.newMsgCount)
}
.accentColor(Color("AccentColor"))
.onAppear() {
if firstAppear {
messenger.getAllMessages()
firstAppear = false
}
}
.environmentObject(messenger)
}
}
MessengerViewModel.swift: (shortened for SO. Even this small sample causes the same issue)
class MessagingViewModel: ObservableObject {
@Published var newMsgCount = 0
init(){// connect socket...}
func setUpChatListener() {
DispatchQueue.main.async {
self.manager.defaultSocket.on("Private Message") { data, ack in
do {
self.newMsgCount += 1
//do what ever else I need to do with the chat...
} catch let err {
print(err)
}
}
}
}
}
I've really hit a roadblock with this one. Am I going to have to use Apple's push system? I find it odd that I can't just reload the little icon to show the new message count rather than reloading the entire thing.