0

I have a set of NSOperations which make network requests. Imagine a case where we have a User object in Realm and I want to make some changes and then send a PATCH request to the server:

let operation = UpdateUserOperation(updatedUser)

Then the operation runs on a different thread so it has to resolve a thread safe reference:

class UpdateUserOperation : Operation {
    var userReference : ThreadSafeReference<User>

    init(_ user: User) {
        userReference = ThreadSafeReference(to: user)
    }

    func main() {
        // We're probably on a different thread so resolve the reference
        let user = try! Realm().resolve(userReference)

        // That invalidated `userReference` so we need to create a new
        // one to use below...
        userReference = ThreadSafeReference(to: user)

        sendUserPatchRequest(user) { response in
            // We might be in _another_ thread again :(
            let realm = try! Realm()
            let user = realm.resolve(userReference)
            try! realm.write {
                user.updateFromResponse(response)
            }
        }
    }
}

This feels like a really unclean way to do this – re-fetching the user so many times to do a pretty simple task. It feels especially onerous because we need to re-up the thread-safe reference – they aren't re-usable. In Core Data, we'd be able to choose a single NSManagedObjectContext to do our work in and ensure thread safety by using managedObjectContext.perform { /* ... */ }, but that sort of functionality is unavailable in Realm.

Am I missing anything? Is there a better way to do this, or am I stuck re-fetching the object each time I need to use it?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
jsadler
  • 589
  • 4
  • 18
  • In Realm-Android you generally re-fetch it by ID because realm-android doesn't support ThreadSafeReference. But in a way, it is cleaner to look at. – EpicPandaForce Jan 18 '19 at 21:34
  • You have several ways to get around thread safety. You can create a reference to your Realm from the thread you're currently on after switching between threads or you can always access your Realm from a specific `DispatchQueue`. I'd suggest you take a look at [my answer for a similar question about ThreadSafeReference](https://stackoverflow.com/a/45375608/46678350) and passing Realm objects between threads in general. – Dávid Pásztor Jan 21 '19 at 14:22

0 Answers0