Transform an object to a list[object] in Realm as migration ( How can i replace a list[objects] with object field in Realm? )

前端 未结 1 1467
终归单人心
终归单人心 2020-12-22 00:48

I want to import existing token into tokenList as first item , for example if someone has a token=\"abc\" after migration

相关标签:
1条回答
  • 2020-12-22 01:35

    I created new issue in Realm GitHub then i found right way for transform object to list[object] in Realm and insert existing object from previous version to new version of application.

    In this example we want to transform Token object to tokenList[Token] in Bank model.

    In last version of migration put this :

    public class RealmMigration implements io.realm.RealmMigration {
    
    .
    
    .
    
    .
    
            if (oldVersion == 3) {
                //Create a schema for Bank
                final RealmObjectSchema bankSchema = realmSchema.get("Bank");
                //Create a schema for Token that has been in Bank model
                final RealmObjectSchema tokenSchema = realmSchema.get("Token");
                //We use bankSchema for add tokenList field and transform
                bankSchema
                    .addRealmListField("tokenList", tokenSchema)
                    .transform((obj) -> {//obj is bank model,we have a transform in bank model
                             DynamicRealmObject token = obj.get("Token");
                             List<DynamicRealmObject> tokenList = obj.get("tokenList");
                                    //We add token from pre version to tokenList in new version
                                    if (token != null) tokenList.add(token);
                                }
                        )
                        //Finally remove unwanted field
                        .removeField("Token");
            }
    }
    
    0 讨论(0)
提交回复
热议问题