ios: stopped state for DB management, suspend quicker/instantly on app termination (#783)

* ios: stopped state for DB management, suspend quicker/instantly on app termination

* update terminateChat
This commit is contained in:
Evgeny Poberezkin
2022-07-06 14:07:27 +01:00
committed by GitHub
parent 6b89eb872b
commit 95f518a582
4 changed files with 37 additions and 6 deletions

View File

@@ -75,6 +75,11 @@ class AppDelegate: NSObject, UIApplicationDelegate {
}
}
func applicationWillTerminate(_ application: UIApplication) {
logger.debug("AppDelegate: applicationWillTerminate")
terminateChat()
}
private func receiveMessages(_ completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let complete = BGManager.shared.completionHandler {
logger.debug("AppDelegate: completed BGManager.receiveMessages")

View File

@@ -16,6 +16,8 @@ let appSuspendTimeout: Int = 15 // seconds
let bgSuspendTimeout: Int = 5 // seconds
let terminationTimeout: Int = 3 // seconds
private func _suspendChat(timeout: Int) {
appStateGroupDefault.set(.suspending)
apiSuspendChat(timeoutMicroseconds: timeout * 1000000)
@@ -25,9 +27,11 @@ private func _suspendChat(timeout: Int) {
func suspendChat() {
suspendLockQueue.sync {
if appStateGroupDefault.get() != .stopped {
_suspendChat(timeout: appSuspendTimeout)
}
}
}
func suspendBgRefresh() {
suspendLockQueue.sync {
@@ -37,17 +41,35 @@ func suspendBgRefresh() {
}
}
func terminateChat() {
suspendLockQueue.sync {
switch appStateGroupDefault.get() {
case .suspending:
// suspend instantly if already suspending
_chatSuspended()
apiSuspendChat(timeoutMicroseconds: 0)
case .stopped: ()
default:
_suspendChat(timeout: terminationTimeout)
}
}
}
func chatSuspended() {
suspendLockQueue.sync {
if case .suspending = appStateGroupDefault.get() {
logger.debug("chatSuspended")
_chatSuspended()
}
}
}
private func _chatSuspended() {
logger.debug("_chatSuspended")
appStateGroupDefault.set(.suspended)
if ChatModel.shared.chatRunning == true {
ChatReceiver.shared.stop()
}
}
}
}
func activateChat(appState: AppState = .active) {
suspendLockQueue.sync {

View File

@@ -223,6 +223,7 @@ struct DatabaseView: View {
try await apiStopChat()
ChatReceiver.shared.stop()
await MainActor.run { m.chatRunning = false }
appStateGroupDefault.set(.stopped)
} catch let error {
await MainActor.run {
runChat = true
@@ -307,6 +308,7 @@ struct DatabaseView: View {
do {
try initializeChat(start: true)
m.chatDbChanged = false
appStateGroupDefault.set(.active)
} catch let error {
fatalError("Error starting chat \(responseError(error))")
}
@@ -318,6 +320,7 @@ struct DatabaseView: View {
m.chatRunning = true
ChatReceiver.shared.start()
chatLastStartGroupDefault.set(Date.now)
appStateGroupDefault.set(.active)
} catch let error {
runChat = false
alert = .error(title: "Error starting chat", error: responseError(error))

View File

@@ -23,6 +23,7 @@ public enum AppState: String {
case bgRefresh
case suspending
case suspended
case stopped
public var inactive: Bool {
switch self {