在 Swift Combine 上的不同 DispatchQueue 上创建自定义发布者 运行
Make custom Publisher run on a different DispatchQueue on Swift Combine
我创建了一个函数,returns 一个自定义发布者 Swift 结合使用下面的代码:
func customPubliher() -> AnyPublisher<Bool, Never> {
return Future<Bool, Never> { promise in
promise(.success(true))
}.eraseToAnyPublisher()
}
然后我使用以下代码订阅了这个发布者:
customPublisher()
.subscribe(on: DispatchQueue.global())
.map { _ in
print(Thread.isMainThread)
}
.sink(receiveCompletion: { _ in }, receiveValue: { value in
// Do something with the value received
}).store(in: &disposables)
但是即使我在订阅时添加了行 .subscribe(on: DispatchQueue.global())
,代码 not 在不同的队列中执行(print
在.map
输出 true)。
但是,如果我用一个内置的 Combine 发布者替换我的自定义发布者,例如 Just()
(见下文),相同的代码在不同的队列上执行得很好:
Just(true)
.subscribe(on: DispatchQueue.global())
.map { _ in
print(Thread.isMainThread)
}
.sink(receiveCompletion: { _ in }, receiveValue: { value in
// Do something with the value received
}).store(in: &disposables)
上面代码中的 .map
输出 false。
我在使用自定义发布器时做错了什么?我希望它 运行 在不同的队列中,就像 Just()
发布者所做的那样。
在我对您的代码的测试中,我得到 false
。实际上 DispatchQueue
与某个特定线程没有一对一关系,它是一个执行队列并指定 DispatchQueue.global()
你要求系统 select 一些空闲队列 以 默认优先级 执行您的任务。因此,由系统决定在哪个队列和哪个线程中执行您的任务。
如果您有意将其强制置于后台,请使用
.subscribe(on: DispatchQueue.global(qos: .background))
我创建了一个函数,returns 一个自定义发布者 Swift 结合使用下面的代码:
func customPubliher() -> AnyPublisher<Bool, Never> {
return Future<Bool, Never> { promise in
promise(.success(true))
}.eraseToAnyPublisher()
}
然后我使用以下代码订阅了这个发布者:
customPublisher()
.subscribe(on: DispatchQueue.global())
.map { _ in
print(Thread.isMainThread)
}
.sink(receiveCompletion: { _ in }, receiveValue: { value in
// Do something with the value received
}).store(in: &disposables)
但是即使我在订阅时添加了行 .subscribe(on: DispatchQueue.global())
,代码 not 在不同的队列中执行(print
在.map
输出 true)。
但是,如果我用一个内置的 Combine 发布者替换我的自定义发布者,例如 Just()
(见下文),相同的代码在不同的队列上执行得很好:
Just(true)
.subscribe(on: DispatchQueue.global())
.map { _ in
print(Thread.isMainThread)
}
.sink(receiveCompletion: { _ in }, receiveValue: { value in
// Do something with the value received
}).store(in: &disposables)
上面代码中的 .map
输出 false。
我在使用自定义发布器时做错了什么?我希望它 运行 在不同的队列中,就像 Just()
发布者所做的那样。
在我对您的代码的测试中,我得到 false
。实际上 DispatchQueue
与某个特定线程没有一对一关系,它是一个执行队列并指定 DispatchQueue.global()
你要求系统 select 一些空闲队列 以 默认优先级 执行您的任务。因此,由系统决定在哪个队列和哪个线程中执行您的任务。
如果您有意将其强制置于后台,请使用
.subscribe(on: DispatchQueue.global(qos: .background))