Realm.open vs new Realm

ε祈祈猫儿з 提交于 2019-12-06 06:03:02

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/48668497/realm-open-vs-new-realm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!