Background or Main Thread Advice


Looking for advice on using background or main thread processes with Realm Swift

The use case is we have a massive dataset that is imported from text files and stored in Realm for user consumption. The import process can take several hours so we wan to keep the UI responsive so a lot of the processing is done on background queues, including Realm tasks to write the data out.

Because of that, all of the Realm objects are created on a background thread. When the processing is completed users query Realm for small sets of data which could be done on the main queue. However since the Realm objects were written on the background thread, they would need to be read on the background thread.

Is there a best practice to work with Realm either on a background or a main? Is using background across the app for all Realm functions a typical use?

It seems clunky to create a DispatchQueue every time we want to read/write to Realm; here’s an example of reading all of the dogs objects on a background queue; is this optimal?

DispatchQueue(label: "background").async {
            autoreleasepool {
                let realm = RealmService.shared.realm
                let dogs = realm.objects(DogClass.self)
                for dog in dogs {
                     print(dog.dog_name, dog.dog_id)


class RealmService {
    static let shared = RealmService()
    lazy var realm: Realm = {
        let realmClassArray = [DogClass.self]
        let syncConfig = SyncConfiguration(user: SyncUser.current!, realmURL: Constants.REALM_URL)

        let realm = try! Realm(configuration: Realm.Configuration(syncConfiguration: syncConfig, objectTypes:realmClassArray))

        return realm


We always use realm on a dedicated thread - it’s easier to manage the object lifecycle.

We have a factory-manager architect. The factories working on the realm thread and the managers are handling the thread changes on the object. Also, they convert the realm object to a simple struct, to use them on the screens.

I don’t see any performance issues, we use something like 50 transactions per minute.
But if somebody has a better idea, then please tell me, I’m open to refactor things :smiley: