Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make custom Publisher run on a different DispatchQueue on Swift Combine

Tags:

ios

swift

combine

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.

like image 684
vegidio Avatar asked Nov 12 '19 08:11

vegidio


1 Answers

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))
like image 193
Asperi Avatar answered Oct 09 '22 10:10

Asperi