Skip to content

Commit

Permalink
Add main func for synchronous work to override
Browse files Browse the repository at this point in the history
  • Loading branch information
wuyuehyang committed Mar 8, 2022
1 parent 5539e46 commit 9d9d51f
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 8 deletions.
5 changes: 1 addition & 4 deletions Mixin/Service/Work/AttachmentCleaningWork.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ final class AttachmentCleaningWork: Work {
super.init(id: "attachment_clean", state: .ready)
}

override func start() {
super.start()
override func main() throws {
guard -AppGroupUserDefaults.User.lastAttachmentCleanUpDate.timeIntervalSinceNow >= 7 * .oneDay else {
state = .finished(.cancelled)
return
}

Expand Down Expand Up @@ -58,7 +56,6 @@ final class AttachmentCleaningWork: Work {
}

AppGroupUserDefaults.User.lastAttachmentCleanUpDate = Date()
state = .finished(.success)
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ public final class DeleteMessageWork: Work {
super.init(id: "delete-message-\(messageId)", state: .ready)
}

override public func start() {
super.start()
public override func main() throws {
if !hasDatabaseRecordDeleted {
MessageDAO.shared.delete(id: messageId, conversationId: conversationId)
}
Expand All @@ -79,7 +78,6 @@ public final class DeleteMessageWork: Work {
case .none:
break
}
state = .finished(.success)
}

}
Expand Down
12 changes: 12 additions & 0 deletions MixinServices/MixinServices/Services/Work/Work.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,20 @@ open class Work {
}
}

// Override this if you want precisely control of state
open func start() {
state = .executing
do {
try main()
state = .finished(.success)
} catch {
state = .finished(.failed(error))
}
}

// Override this for straight synchronous works
open func main() throws {

}

open func cancel() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public class WorkManager {
completion: work.persistenceDidComplete)
}
if work.isReady, executingWorks.count < maxConcurrentWorkCount {
Logger.general.debug(category: "WorkManager", message: "[\(label)] Execute \(work) because of adding to queue")
Logger.general.debug(category: "WorkManager", message: "[\(label)] Start \(work) because of adding to queue")
executingWorks.insert(work)
dispatchQueue.async(execute: work.start)
} else {
Expand Down

0 comments on commit 9d9d51f

Please sign in to comment.