Skip to content

Commit aca2a26

Browse files
committed
解决非主进程报错问题
1 parent 8725f00 commit aca2a26

1 file changed

Lines changed: 15 additions & 6 deletions

File tree

Sources/TaskKit/ViewModels/EventCenter.swift

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
//
55
// Created by xuehui yang on 2025/12/6.
66
//
7-
public enum TaskEvent: Codable {
7+
public enum TaskEvent: Codable , Sendable {
88
case openPage(String)
99
case finishFeature(String)
1010
case tapButton(String)
@@ -50,21 +50,30 @@ public enum TaskEvent: Codable {
5050
}
5151
}
5252

53-
5453
@MainActor
55-
public final class EventCenter : @unchecked Sendable {
54+
public final class EventCenter {
55+
5656
public static let shared = EventCenter()
5757
private init() {}
5858

59-
private var subscribers: [@MainActor (TaskEvent) -> Void] = []
59+
private var subscribers: [(TaskEvent) -> Void] = []
60+
61+
/// 外部任何线程都可以调用
62+
public nonisolated func send(_ event: TaskEvent) {
63+
let eventCopy = event // ⭐ 关键
64+
Task { @MainActor in
65+
self.dispatch(eventCopy)
66+
}
67+
}
68+
6069

61-
public func send(_ event: TaskEvent) {
70+
private func dispatch(_ event: TaskEvent) {
6271
for handler in subscribers {
6372
handler(event)
6473
}
6574
}
6675

67-
public func subscribe(_ handler: @escaping @MainActor @Sendable (TaskEvent) -> Void) {
76+
public func subscribe(_ handler: @escaping (TaskEvent) -> Void) {
6877
subscribers.append(handler)
6978
}
7079
}

0 commit comments

Comments
 (0)