Search code examples
androidrealm

Getting @LinkingObjects backlink in unmanaged RealmObject?


with the new 3.4.0 realm version we are able to get automatick backlinks via @LinkingObject, works, however, is there a way I can get these backlinks in unmanaged state? Backlinking realm results are aways null


Solution

  • Considering you need to define backlinks as

    @LinkingObjects("linkingObjectsField")
    private final RealmResults<OtherObject> backlink = null;
    

    And realm.copyFromRealm() ignores backlinks, unmanaged objects can't have the backlink field set. Generally, you wouldn't need to access backlinks in a detached object.

    So a possible workaround would be

    @LinkingObjects("linkingObjectsField")
    private final RealmResults<OtherObject> backlink = null;
    
    @Ignore
    private List<OtherObject> unmanagedBacklink = Collections.emptyList();
    
    public <T extends List<OtherObject>> T getBacklinkObjects() {
        if(isManaged()) {
            // noinspection unchecked
            return (T)backlink; // <-- so that this can be obtained as RealmResults<T>
        } else {
            // noinspection unchecked
            return (T)unmanagedBacklink;
        }
    }
    

    And you can manually copy the backlinks with realm.copyFromRealm(obj.getBacklink()); on a managed instance of obj.


    Or just use a managed object, considering I do not see the use-case where you need unmanaged backlinks (other than maybe sending them through GSON, but even then I generally recommend having explicit DTO classes instead).