TSBaseOperation.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. //
  2. // TSBaseOperation.swift
  3. // AIRingtone
  4. //
  5. // Created by 100Years on 2025/3/20.
  6. //
  7. import Foundation
  8. class TSBaseOperation: Operation , @unchecked Sendable{
  9. let uuid:String
  10. enum TSBaseOperationState {
  11. case executing(Bool)
  12. case finished(Bool)
  13. case cancelled(Bool)
  14. }
  15. @Published var operationStatePblished:TSBaseOperationState = .executing(false)
  16. private var _executing = false
  17. private var _finished = false
  18. private var _cancelled = false
  19. private var _error: Error?
  20. required init(uuid:String) {
  21. self.uuid = uuid
  22. super.init()
  23. }
  24. // MARK: - State Management
  25. override var isExecuting: Bool {
  26. return _executing
  27. }
  28. override var isFinished: Bool {
  29. return _finished
  30. }
  31. override var isCancelled: Bool {
  32. return _cancelled
  33. }
  34. override var isAsynchronous: Bool {
  35. return true
  36. }
  37. override func start() {
  38. if isCancelled {
  39. finished()
  40. return
  41. }
  42. setExecutingValue(value: true)
  43. }
  44. override func cancel() {
  45. setCancelValue(value: true)
  46. if isExecuting {
  47. finished()
  48. }
  49. }
  50. func finished() {
  51. if _executing {
  52. setExecutingValue(value: false)
  53. }
  54. if !_finished {
  55. setFinishedValue(value: true)
  56. }
  57. }
  58. func setCancelValue(value:Bool){
  59. willChangeValue(forKey: "isCancelled")
  60. _cancelled = value
  61. didChangeValue(forKey: "isCancelled")
  62. operationStatePblished = .cancelled(value)
  63. }
  64. func setExecutingValue(value:Bool){
  65. willChangeValue(forKey: "isExecuting")
  66. _executing = value
  67. didChangeValue(forKey: "isExecuting")
  68. operationStatePblished = .executing(value)
  69. }
  70. func setFinishedValue(value:Bool){
  71. willChangeValue(forKey: "isFinished")
  72. _finished = value
  73. didChangeValue(forKey: "isFinished")
  74. operationStatePblished = .finished(value)
  75. }
  76. // MARK: - Error Handling
  77. var error: Error? {
  78. return _error
  79. }
  80. // MARK: - Convenience Methods
  81. override func waitUntilFinished() {
  82. while !isFinished {
  83. RunLoop.current.run(mode: .default, before: .distantFuture)
  84. }
  85. }
  86. func addDependency(_ operation: TSBaseOperation) {
  87. super.addDependency(operation)
  88. }
  89. func removeDependency(_ operation: TSBaseOperation) {
  90. super.removeDependency(operation)
  91. }
  92. deinit {
  93. dePrint("TSBaseOperation deinit")
  94. }
  95. }