Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to connect Realm and SwiftBond

I love Realm and I love Bond. Both of them makes app creation a joy. So I was wondering what is the best way to connect Realm and Bond?
In Realm we can store basic types such as Int, String, e.g. But in Bond we work with Dynamics and Bonds. The only way that I found to connect Realm and Bond is following:

class TestObject: RLMObject {

   dynamic var rlmTitle: String = ""
   dynamic var rlmSubtitle: String = ""

   var title: Dynamic<String>
   var subtitle: Dynamic<String>

   private let titleBond: Bond<String>!
   private let subtitleBond: Bond<String>!

   init(title: String, subtitle: String) {
      self.title = Dynamic<String>(title)
      self.subtitle = Dynamic<String>(subtitle)

      super.init()

      self.titleBond = Bond<String>() { [unowned self] title in self.rlmTitle = title }
      self.subtitleBond = Bond<String>() { [unowned self] subtitle in self.rlmSubtitle = subtitle }

      self.title ->> titleBond
      self.subtitle ->> subtitleBond
   }
}

But it surely lacks simplicity and elegance and produces a lot of boiler code. Is there any way to do this better?

like image 581
Nikita Arkhipov Avatar asked Feb 11 '23 15:02

Nikita Arkhipov


1 Answers

With Realm supporting KVO and Bond 4, you can extend Realm objects to provide Observable variants. There is some boilerplate to it, but it's clean and without hacks.

class Dog: Object {
  dynamic var name = ""
  dynamic var birthdate = NSDate(timeIntervalSince1970: 1)
}

extension Dog {

  class ObservableDog {
    let name: Observable<String>
    let birthdate: Observable<NSDate>

    init(dog: Dog) {
      name = Observable(object: dog, keyPath: "name")
      birthdate = Observable(object: dog, keyPath: "birthdate")
    }
  }

  func observableVariant() -> Dog.ObservableDog {
    return ObservableDog(dog: self)
  }
}

Than you'll be able to do:

let myDog = Dog().observableVariant()

myDog.name.observe { newName in
  print(newName)
}

myDog.name.bindTo(nameLabel.bnd_text)

realm.write {
  myDog.name.value = "Jim"
}
like image 80
Srđan Avatar answered Feb 13 '23 06:02

Srđan