Search code examples
javaandroidjsonrealmrealm-java

Realm createOrUpdateAllFromJson to create RealmModel objects without persisting?


I'm using realm Java in my in-development Android app quite happily. I receive JSONObject arrays from the server API, and realm dutifully ingests them through the convenient createOrUpdateAllFromJson on the main realm instance object.

The typical flow for this looks like:

// get API results into JSONArray jsonObjArrs variable
realm.beginTransaction();
realm.createOrUpdateAllFromJson(MyCoolModel.class,jsonObjArrs);
realm.commitTransaction();

However, I've now run into a situation where I would like to create a temporary, in-memory array of the same MyCoolModel objects without actually saving them to Realm, because I want to throw these away as soon as the specific use case is done. It looks to me like createOrUpdateAllFromJson and its sibling methods are only available on the main realm instance object.

Is there any way to harness this convenient JSON to object model creator, or do I have to write an alternate implementation with manual / automated JSON parsing?


Solution

  • I ended up using the "In memory Realm" feature of realm. I wrote a simple function that would return a new in-memory realm instance, with a new UUID as a name:

    public Realm unpersistedRealm(){
        RealmConfiguration myConfig = new RealmConfiguration.Builder()
                .name(UUID.randomUUID().toString())
                .inMemory()
                .build();
        return Realm.getInstance(myConfig);
    }
    

    I use this as a separately created instance just for throw-away data purposes. I create the objects using the normal inMemoryRealmInstance.createOrUpdateAllFromJson() call and close the in memory instance the moment I'm done. I create the instance during my fragment's onCreateView() call and close the realm in onDestroyView().

    Continuing to use realm (albeit an in-memory instance) gives me the following distinct advantages:

    • In built de-duplication using @PrimaryKey on my MyCoolModel key field. If I were to use the manual ArrayList<MyCoolModel> approach that I was earlier thinking of, I'd have to manually de-duplicate, and worry about other headaches that Realm already solved for me.
    • Query based sorting, filtering, etc.