【问题标题】:Counters custom conflict resolution in realm mobile platform for android在适用于 android 的领域移动平台中计数器自定义冲突解决
【发布时间】:2016-12-27 21:24:47
【问题描述】:

我想为此场景设置自定义分辨率: 1- 在离线模式下在一台设备中增加领域对象中的整数字段 2-在离线模式下增加另一个设备中相同领域对象中的相同整数字段 默认的自定义分辨率是最后一次更新获胜,但在我的情况下我想要 两个设备中的增量在上线而不是最后一次更新后对结果生效。 我尝试了这段代码进行测试:

Realm realm = Realm.getDefaultInstance();
            final RealmResults<Number> results= realm.where(Number.class).findAll();

            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    int num = results.get(0).getNumber()+1;
                    results.get(0).setNumber(num);
                }
            });

Number 类是这样的:

public class Number extends RealmObject {
@PrimaryKey
private String id;
private int number;

public String getId() {
    return id;
}
public void increment(){
    this.number++;
}
public void setId(String id) {
    this.id = id;
}

public int getNumber() {
    return number;
}

public void setNumber(int number) {
    this.number = number;
}

这个问题对我的应用非常关键。如果我不能在客户端这样做 我将无法使用我非常感兴趣的领域移动平台。

【问题讨论】:

    标签: android realm realm-mobile-platform


    【解决方案1】:

    也许您可以对此类对象使用命令列表,将它们保持在离线状态并在上线时同步/合并。命令可以是 increment、decrement、multiplyBy2 等。

    文档说:

        Inserts in lists are ordered by time. 
        If two items are inserted at the same position, the item that was
        inserted first will end up before the other item. This means that
        if both sides append items to the end of a list they will end up in
        order of insertion time.
    

    因此,您将始终拥有按日期排序的应用命令列表。

    【讨论】:

    • 我知道可以将方法放在 ArrayList 中,但我不知道如何在联机时运行这些方法。请你在代码中给出一个例子。
    【解决方案2】:

    文档目前说协议支持计数器,但还没有在语言级别公开,所以我想你必须自己实现它。

    最简单的方法是将其存储为整数的List(1 用于递增,-1 用于递减),然后使用List.sum()(https://realm.io/docs/java/2.2.1/api/io/realm/RealmList.html#sum-java.lang.String-)快速获得聚合结果.

    public class Counter extends RealmObject {
        private int count;
    
        public int    getCount() { return count; }
        public void   setCount(int count) { this.count = count; }
    }
    
    public class Number extends RealmObject {
        @PrimaryKey
        private String id;
        private RealmList<Counter> counters;
    
        public void incrementNumber(){
            Counter c = realm.createObject(Counter.class);
            c.setCount(1);
            this.getCounters().add(c);
        }
    
        public int getNumber() {
            // Get the aggregate result of all inc/decr
            return this.getCounters().sum("count");
        }
    
        public void setNumber(int number) {
            this.getCounters().deleteAllFromRealm();
    
            Counter c = realm.createObject(Counter.class);
            c.setCount(number);
            this.getCounters().add(c);
        }
    
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        private RealmList<Counter> getCounters() { return counters; }
        private void setCounters(RealmList<Counter> counters) { this.counters = counters; }
    }
    

    ```

    【讨论】:

    • 假设我们的应用程序在没有设置数字的情况下主要是递增或递减,那么列表将快速增长。我正在考虑何时以及如何清空列表。
    • 您可以定期压缩列表(只需将所有值替换为总和的单个值),或者当超过特定大小时。如果在服务器端完成,那将是最有效的(但只要只有一台设备可以进行压缩,它将是安全的)。
    • 设备上线时,我已将列表替换为 sum 值。但是由于领域是一个同步的领域,我们首先应该在设备上获取服务器数据,然后求和并清空列表。虽然仍然没有 callabck 知道同步何时完成。我在上线后延迟了 10 秒,让应用有足够的时间与服务器同步。
    • 我们在 repo 中的 Realm 移动平台示例,实际上实现了一个计数器:github.com/realm/realm-java/tree/master/examples/…
    【解决方案3】:

    感谢@ast 代码示例。我还通过缓存命令模式解决了这个问题,这是我的代码:

    public class CommandPattern extends RealmObject {
    @PrimaryKey
    private String id;
    private String commandName;
    
    public String getCommandName() {
        return commandName;
    }
    
    public void setCommandName(String commandName) {
        this.commandName = commandName;
    }
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }}
     @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_increment:
                if (isOnline()) {
                    realm = Realm.getDefaultInstance();
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            updateNumberOnRealm();
                        }
                    });
                    realm.close();
                } else {
                    addMethodToCache("increment");
                }
    public void addMethodToCache(final String methodName) {
        realm = Realm.getDefaultInstance();
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                commandPattern = new CommandPattern();
                commandPattern.setId(UUID.randomUUID().toString());
                commandPattern.setCommandName(methodName);
                realm.copyToRealmOrUpdate(commandPattern);
            }
        });
        realm.close();
    }
    
    public void invokeCachedCommands() {
        realm = Realm.getDefaultInstance();
        commandsCached = realm.where(CommandPattern.class).findAll();
        commandsCached.addChangeListener(new RealmChangeListener<RealmResults<CommandPattern>>() {
            @Override
            public void onChange(final RealmResults<CommandPattern> element) {
                if(!element.isEmpty()) {
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            for (CommandPattern command : element) {
                                if(command != null) {
                                    if (command.getCommandName().equals("increment")) {
                                        //updateNumberOnRealm();
                                        RealmResults<Number> results = realm.where(Number.class).findAll();
                                        results.get(0).increment();
                                        command.deleteFromRealm();
                                    }
                                }
                            }
                        }
    
                    });
                }
            }
    
        });
    
    
        realm.close();
    
    }
    

    在完成增量操作之前,我检查在线状态,如果它离线,则缓存在命令模式对象中的增量字符串 再次上线后,这些缓存的命令会被以下代码调用:

    IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
                if (isNetworkAvailable) {
                    invokeCachedCommands();
                }else{
                    if(commandsCached != null) {
                        commandsCached.removeChangeListeners();
                    }
                }
    
            }
        }, intentFilter);
    

    这是通用的自定义冲突解决方案,可用于任何类型的命令

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 2014-09-17
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      相关资源
      最近更新 更多