Skip to content

get Realm instance from RealmObject #4720

@yamamotoj

Description

@yamamotoj

Goal

To get Realm instance from RealmObject inheriting object when it is managed.
It was possible in the previous version ( e.g. 0.87.2).

Use Case

Our application have something like news feed.
The feed item has several kind of information.
In the new feed list view, almost same information is displayed for all kind of item.
When an user tap the feed list item in the feed list view,
a kind specific detail feed information is displayed in addition to common feed item information.

I am realizing following data structure on Realm 0.87.2.

realm_meet_up__9____speaker_deck

FeedItem class is a realm object for common feed list item information,
A realm object for kind specific detail feed information is defined for each kind,
and implements FeedItemDetail interface.

To realize polymorphism like behaviour which is not supported by realm object,
I add getFeedDetail() method with FeedItemDetail return type to FeedItem class with @ignored annotation.
In the getFeedDetail(), I get Realm instance and find feed detail object instance with realm query.
It was possible, because I could get Realm from RealmObject.
So I want make RealmObject to get realm instance.

Sample codes are like this.

public interface FeedItemDetail{
   /* ... */
}

public class CardUpdateDetail extends RealmObject implements FeedItemDetail{

    @PrimaryKey
    private String feedId;

    /* ... */
}

public class SharedLinkDetail extends RealmObject implements FeedItemDetail{

    @PrimaryKey
    private String feedId;

    /* ... */
}

public class FeedItem extends RealmObject{

    /** kind of feed item */
    private int kind;
    @Ignored
    private FeedItemDetail feedItemDetail;

    FeedItemDetail getFeedItemDetail(){
         if(this.feedItemDetail != null){
            return this.feedItemDetail;
        }
        switch(this.kind){
            case FEED_ITEM_KIND_CARD_UPDATE:
                this.feedItemDetail = getRealm().where(CardUpdateDetail::class).equals("id", id).first()
                return this.feedItemDetail;
            case FEED_ITEM_KIND_SHARED_LINK:
                this.feedItemDetail = getRealm().where(SharedLinkDetail::class).equals("id", id).first()
                return this.feedItemDetail;
            case .....
        }
    }
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions