Background Threads/Queues in SwiftUI

Updated:

Background Threads/Queues in SwiftUI

Basically behind the scenes in your app there are a bunch of different threads that we can do processes on that we can perform tasks on.

The main thread can on a lot of tasks but if you start developing more complex apps, you’re going to end up doing a lot of stuff on the main thread and if you do too much it will start to slow down you app. It could cause your app to freeze and possibly even crash

So, as professional developer is take some of our heavy tasks are happening in the background like downloading from the internet we can download images all that we could put on a background thread and basically all we have that instead of ruining this on the main thread run it on a background thread.

There are a whole bunch of background threads that we can choose from and Apple actually provides us an easy way to access a bunch of those background threads

The one of important thing about threading is to remember that anything that updates the UI so updates the actual screen needs to be performed on the main thread

  • Go to show debug navigator on me menu bar and click CPU, you can see the usage of CPU and Threads

image

In Thread section, this is all of the threads in our app and you can think of these kind of as engines.

So, Thread 1 is the main engine it’s called the main thread and this is where almost all of the code that you write will happen by default on the Thread 1.

Here is Sample of data fetching to show thread spike on it. (Code and Screenshot)

import SwiftUI

// MARK: -  VIEWMODEL
class BackgroundThreadViewModel: ObservableObject {
// MARK: -  PROPERTY
@Published var dataArray: [String] = []

// MARK: -  INIT
// MARK: -  FUNCTION
func fetchData() {
  let newData = downloadData()
  dataArray = newData
}

// Create fake data as to download data from Internet
private func downloadData()-> [String] {
  var data: [String] = []

  for x in 0..<100 {
    data.append("\(x)")
    print(data)
  }
  return data
}
}

struct BackgroundThreadBootCamp: View {
// MARK: -  PROPERTY
@StateObject var vm = BackgroundThreadViewModel()

// MARK: -  BODY
var body: some View {
ScrollView {
VStack (spacing: 10) {
  Text("LOAD DATA")
    .font(.largeTitle)
    .fontWeight(.semibold)
    .foregroundColor(.white)
    .padding(10)
    .frame(height: 55)
    .frame(maxWidth: .infinity)
    .background(Color.blue.cornerRadius(10))
    .onTapGesture {
      vm.fetchData()
    }

  ForEach(vm.dataArray, id: \.self) {
    Text($0)
      .font(.headline)
      .foregroundColor(.red)
  } //: LOOP
} //: VSTACK
.padding()
} //: SCROLL
}
}

image

You can see that this happened on the main thread you can scrolling all around the screen you’ll see that all that all that functionally is happening on our main thread

The main thread is pretty powerful we can do a tons of stuff on the main thread without ever having problems

But, when you have too many tasks going on this main thread it will get kind of stuck and it will slow down and when the thread slows down entire app will to slow down

The solution here is to offload some of these tasks to a background thread to lose the burden of main thread

image

// MARK: -  FUNCTION
func fetchData() {

// we can use the regular global completion here you can use the global and specity a quality of
// service
// qos: the period on this quality of service there are a couple of different background queue that we can use
DispatchQueue.global(qos: .background).async {
let newData = self.downloadData()

print("Chcke 1: \(Thread.isMainThread)")
print("Chcke 1: \(Thread.current)")

// anytime we update this data array it neeeds to be done on the main thread not on the background
// UI updated will be proccesed on the main thread
DispatchQueue.main.async {
  self.dataArray = newData
  print("Chcke 2: \(Thread.isMainThread)")
  print("Chcke 2: \(Thread.current)")

}
}
}

image

image



🗃 Reference

SwiftUI Thinking - https://www.youtube.com/watch?v=jEpg2SYvVV8&list=PLwvDm4VfkdpiagxAXCT33Rkwnc5IVhTar&index=18

Categories:

Updated:

Leave a comment