Search code examples
swiftrealm

How to correctly use shouldCompactOnLaunch in RealmSwift


The example in the documentation (https://realm.io/docs/swift/latest/#compacting-realms) is not very clear to me, as I don't know if the compaction could be called all the time during app use or only once at startup. Is the implementation below correct or would it be better to make a separate config including shouldCompactOnLaunch to call once on app launch.

If I add shouldCompactOnLaunch to the default configuration I see the block being called every time I create a realm instance.

        Realm.Configuration.defaultConfiguration = Realm.Configuration(schemaVersion: schemaVersion, migrationBlock: migrationBlock,shouldCompactOnLaunch: { totalBytes, usedBytes in
        // totalBytes refers to the size of the file on disk in bytes (data + free space)
        // usedBytes refers to the number of bytes used by data in the file

        // Compact if the file is over 100MB in size and less than 50% 'used'
        let oneHundredMB = 100 * 1024 * 1024
        print ("totalbytes \(totalBytes)")
        print ("usedbytes \(usedBytes)")
        if (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.7{
            print("will compact realm")
        }
        return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.7
    })
    do {
        // Realm is compacted on the first open if the configuration block conditions were met.
        _ = try Realm(configuration: config)
    } catch {
        // handle error compacting or opening Realm
    }

And one more thing would be interesting to me: What happens if the compaction fails? Too little storage would be a reason. Will I still be able to access the data and the compaction will just be skipped?


Solution

  • So the solution for me was to create to configs. The configs are identical except of the shouldCompactOnLaunch block. This config with the shouldCompactOnLaunch I just use once at app launch, so it does not get triggered every time.

    Here is the link to the Realm github issue

    If the compaction fails the app will continue using the uncompacted version of the database.