Swift Combine, Changing Threads As You Want, ‘3’ Common Sense You Must Know
iOS makes threads really easy to use. Almost any concurrency can be resolved with DispatchQueue.main
or DispatchQueue.qos
. You can also use Combine by changing Thread! If you handle threads and combine well, you can avoid being recognized as a beginner anywhere!
Three Common Sense About Combine and Thread
- You can change thread on subscriber
- You can change thread on publisher
- Some publisher must run on
Background
only
What threads are running?
When the intSubject executes the code inside the DispatchQueue.global().async
block, you can see the code being executed in a different thread. Conversely, when intSubject
is not within DispatchQueue.global().async
block, you can see that the code is executed in the main thread. You can see that the thread is automatically converted according to the environment that generates the event.
[1] Change Thread On Subscriber with receive(on:)
What do you think it will happen? Surprisingly, Both intSubject.send(1)
and intSubject.send(2)
will run on main thread. But How? It’s because you added a chain .receive(on: DispatchQueue.main)
. This method allows you to specify which thread you want to run with subscribers!
[2] Change Thread On Publisher with subscribe(on: )
You might have never seen this. Because it’s not used so often. But it’s good to know.
Not only can you specify on which thread your subscriber runs with receive(on: )
,but you can also specify the thread your publisher runs on with subscribe(on:)
.
By specifying this, intSubject.send(1)
will be ignored because your publisher can only run on background thread!
But intSubject.send(2)
will be executed it will finally run on Main Thread.
[3] Some publisher must run on Background
only
If you’re an ios developer, it’s impossible you haven’t used URLSession before. If not, you are not yet an ios developer. URLSession Task is processed in the background and then returns to the main thread to update UI. When you don’t need to update UI, you might let it run on Background.
With combine you can replicate this behavior with receive(on:)
method. However, even if you want to change the thread your publisher runs on with subscribe(on: DispatchQueue.main)
, it simply does not work! Because some publishers are constrained to run on Background Thread!
Conclusion
- You can change thread on subscriber
- You can change thread on publisher
- Some publisher must run on
Background
only