Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm.open vs new Realm

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:

Realm.open:

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

new Realm:

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

like image 743
Xavi A. Avatar asked Feb 07 '18 16:02

Xavi A.


1 Answers

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 :)

like image 130
Marius Meiners Avatar answered Sep 29 '22 19:09

Marius Meiners