【问题标题】:Realm latency between writes in the background thread and retrieving objects in the UI thread?在后台线程中写入和在 UI 线程中检索对象之间的领域延迟?
【发布时间】:2016-06-28 19:26:39
【问题描述】:

在我的应用程序中,我通过后台线程中的领域事务同步所有数据。但是,有时当我尝试在 UI 线程中检索最近同步的对象时,会收到空指针异常。我编写了一个例程,似乎可以解决这个小延迟问题,但感觉就像一个“hacky”解决方案。任何指导将不胜感激。我在下面发布了一个简化版的例程。

private void attemptToEnterActivity(){

    // Retrieve the object's key.
    String key = Application.getInstance().getRecentlySyncedPrimaryKey();

    // Retrieve the realm object with the key.
    Realm realm = Realm.getDefaultInstance();
    Object object = realm.where(Object.class)
            .equalTo("key", key)
            .findFirst();

    if (object != null) {
        new NavigationController(this).activity_start(new Intent(this, Activity.class));
    } else {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                attemptToEnterActivity();
            }
        }, 200);
    }
}

【问题讨论】:

    标签: android multithreading background realm


    【解决方案1】:

    建议使用RealmChangeListener,而不是猜测何时获取和存储对象。有关详细信息,请参阅 doc here

    在您的情况下,您还可以使用 Realm 的异步查询,例如:

    RealmResults<Object> results = realm.where(Object.class)
            .equalTo("key", key).findAllAsync();
    results.addChnageListener(newRealmChangeListener<RealmResults<Object>>() {
            @Override
            public void onChange(RealmResults<Object> objects) {
                if (objects.size() > 0) {
                    Object object = objects.first();
                    // ....
                }
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多