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 Dynamic
s and Bond
s. 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?
You could likely simplify the pattern you're using somewhat if you used default property values:
You could remove another two lines of code if Bond's
->>
operator returned the left value so you could doself.title = Dynamic<String>(title) ->> titleBond
.But ultimately, until Swift has native language support for KVO or an equivalent observation mechanism, you're sadly going to have to write some amount of boilerplate.
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.
Than you'll be able to do:
I've been thinking about this for three days and came up with nearly perfect solution, which does not employ any boilerplate code. First of all I have created a super class for a realm model's wrapper:
After that for each realm model I create two classes, first is the actual realm model, which stores all properties:
and a second one is the wrapper around realm model:
And this two classes is actually all is needed to link
Realm
andBond
: creating newTodoModel
will actually add to Realm newRealmTodoModel
and all changes made withTodoModel
'stitle
anddate
will be automatically saved to correspondingRealm
model!EDIT
I added some functionality and posted this as a framework on GitHub. Here is the link.