I created a function that returns a custom Publisher in Swift Combine using the code below:
func customPubliher() -> AnyPublisher<Bool, Never> {
return Future<Bool, Never> { promise in
promise(.success(true))
}.eraseToAnyPublisher()
}
Then I subscribed to this publisher using the following code:
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)
But even though I added the line .subscribe(on: DispatchQueue.global())
when I do the subscription, the code is not executed in a different queue (the print
in the .map
outputs true).
However, if I replace my custom publisher for one of built-in Combine publishers, for example Just()
(see below), the same code is executed fine on a different queue:
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)
The .map
on the code above outputs false.
What am I doing wrong when I use my custom publisher? I want it to run on a different queue, exactly like the Just()
publisher does.
In my test of your code I'm getting false
. Actually DispatchQueue
has no one-to-one relation with some specific thread, it is a queue of execution and specifying DispatchQueue.global()
you ask system to select some free queue to execute your task with default priority. So it is up to system to decide on which queue and in which thread to execute your task.
If you intentionally want to force it into background, then use
.subscribe(on: DispatchQueue.global(qos: .background))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With