Reputation: 825
In the context of a React Native app, using Realm locally only (so no realm object server for now). What is the difference between opening a realm using
Realm.open({schema: [Car, Person]})
and creating a new Realm instance with new Realm({schema: [Car, Person]});
When should I use one or the other?
Looks like Realm.open
is just a callback to make sure the syncronisation is done, so only needed for synced Realms?
So far this is what I found:
According to the doc reference Realm.open
means "Open a Realm asynchronously with a promise. If the Realm is synced, it will be fully synchronized before it is available." It's the way shown in the js docs
According to the constructor in the doc reference, new Realm
will Create a new Realm instance [...]. If a Realm does not yet exist [...], then this constructor will create it. Otherwise, the instance will access the existing Realm
In the React example they use new: https://github.com/realm/realm-js/blob/master/examples/ReactExample/components/realm.js
Upvotes: 5
Views: 7395
Reputation:
The answer from docs can completely cover your question.
So using sync approach (const realm = new Realm()
) is more simple and appropriate for exporting realm as a module, but it's still preferable to get promise Realm.open()
and handle realm instance when schema migration and sync from remote
server are completed.
Upvotes: 0
Reputation: 125
Is there any specific usecase you have in mind ? Otherwise within react native i havent had to use Realm.open so far. They way i've seen most people approach the architecture is to have a file named realm.js where the schemas are defined and a new Realm is exported like so
class ShoppingCartItem extends Realm.Object{}
ShoppingCartItem.schema = {
name: 'ShoppingCartItem',
primaryKey: 'ordernumber',
properties: {
ordernumber: 'string',
quantity: 'int',
unitPrice: 'double'
}
}
export default new Realm({schema: [User, LastViewedProduct, ShoppingCartItem]});
and then have another file called realmTasks.js where you import that realm object and define actions on it. If you need the realm object in the local state to register changes you can define a callback and give it the realm reference as an argument such as
export function addShoppingCartItem(ordernumber, quantity, unitPrice, callback){
realm.write(() => {
realm.create('ShoppingCartItem', {
ordernumber: ordernumber,
quantity: quantity,
unitPrice: unitPrice
});
})
return callback(realm);
}
I'm not sure if this completely answers your question or is useful to you at all but i hope this gives you a hint :)
Upvotes: 8