0

I want to update some properties of my Realm items in the background after getting data back from an API. Some API calls need to be chained, that is, the result of one call fed to another. PromiseKit looked promising for this, but I'm having trouble staying on the correct thread for Realm.

let utiliQueue = DispatchQueue.global(qos: .utility)

utiliQueue.async {
    autoreleasepool {

        let realm = try! Realm()
        let itemList = DataManager.getSorterFor("ItemList", in: realm).items
        for item in itemList {

            firstly {
                YouTube.getChannelUploadsPlaylistAndBannerURL(item)
            }.done(on: utiliQueue) { (playlistId: String, bannerURL: String) in

                try! item.realm!.write {
                    item.playlistId = playlistId
                    item.bannerImageURL = bannerURL
                }

            }.catch { error in
                print(error.localizedDescription)
            }
        }
    }
}

When I reach the write transaction, I get the IncorrectThreadException from Realm. I've tried telling PromiseKit to run it on the correct DispatchQueue as shown in the code above, but I still get the exception. I am aware of workarounds using Realm objects across threads, but this should be possible on the same thread, right?

Chad Parker
  • 382
  • 3
  • 6

1 Answers1

1

The short answer here is that your code above will use the same dispatch queue for both tasks as you request, but this does not mean that they will run on the same thread. The GCD (Grand Central Dispatch) will use a thread from its threadpool to run each task, but you can’t use dispatch queues to guarantee the same thread is used.

Chris Shaw
  • 1,610
  • 2
  • 10
  • 14