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.