《Android开源库》 Realm For Android~ Threading(译文)

    xiaoxiao2021-03-25  86

    线程

    其实对于跨线程使用 Realm,你需要知道的事情并不多。关键点是得益于对象和查询的即时更新特性,你不需要担心数据在多线程时的一致性和效率问题。

    你可以实时在不同线程中读取和写入 Realm 对象,不用担心其它线程会对同一对象进行操作。你需要在改变对象时使用事务,在另一线程中指向同一对象的数据会被即时更新(更新会在下一次事件循环时进行)。

    唯一局限是你不能随意跨线程传递 Realm 对象。如果你在另一线程使用同一对象,请在哪个线程使用查询重新获得该对象。请谨记所有的 Realm 对象都会在不同线程中保持更新——Realm 会在数据改变时通知你。

    参考如下实例。

    Realm 线程实例

    假设我们的应用要展示一个用户列表。我们在一个后台线程中(一个安卓 IntentService)从远端获取新用户并将它们存储到 Realm 中。但后台线程存储新用户时,UI 线程中的数据会被自动更新。UI 线程会通过 RealmChangeListener 得到通知,这时 UI 线程应刷新相应的控件。因为 Realm 的自动更新特性,无需重新查询数据。

    // in a Fragment or Activity, etc @Override public void onActivityCreated(Bundle savedInstanceState) { // ... boilerplate omitted for brevity realm = Realm.getDefaultInstance(); // get all the customers RealmResults<Customer> customers = realm.where(Customer.class).findAllAsync(); // ... build a list adapter and set it to the ListView/RecyclerView/etc // set up a Realm change listener changeListener = new RealmChangeListener() { @Override public void onChange(RealmResults<Customer> results) { // This is called anytime the Realm database changes on any thread. // Please note, change listeners only work on Looper threads. // For non-looper threads, you manually have to use Realm.waitForChange() instead. listAdapter.notifyDataSetChanged(); // Update the UI } }; // Tell Realm to notify our listener when the customers results // have changed (items added, removed, updated, anything of the sort). customers.addChangeListener(changeListener); } // In a background service, in another thread public class PollingService extends IntentService { @Override public void onHandleIntent(Intent intent) { Realm realm = Realm.getDefaultInstance(); try { // go do some network calls/etc and get some data and stuff it into a 'json' var String json = customerApi.getCustomers(); realm.beginTransaction(); realm.createObjectFromJson(Customer.class, json); // Save a bunch of new Customer objects realm.commitTransaction(); // At this point, the data in the UI thread is already up to date. // ... } finally { realm.close(); } } // ... }

    一旦后台服务添加了新用户,customer 列表会被自动更新,不需要你的任何动作。对于单个的 RealmObject 也是同样。假设你需要管理一个 Realm 对象,只需要在一个线程中更新它的数据,UI 线程会自动得到更新后的数据。如果你需要对数据更新作出回应,只需要添加一个 listener,就像我们在以上代码中所作的一样。

    这就是所有啦。


    跨线程使用 Realm

    请谨记:Realm、RealmObject 和RealmResults 实例都不可以跨线程使用。但是你可以使用异步查询和异步事务来将部分操作放入后台线程进行,待完成时调用线程被通知以获取结果。

    当你需要跨线程访问同一部分数据时,只需简单地在该线程重新获取一个 Realm 实例(例如:Realm.getInstance(RealmConfiguration config) 或是其他类似方法),然后通过这个 Realm 实例来查询获得你需要的数据。查询获得的对象会映射到 Realm 中的相同数据,由此方法获得对象在其线程中任何地方都可读写


    原文链接

    https://realm.io/docs/java/latest/#threading

    onlyloveyd 认证博客专家 Android Kotlin OpenCV 个人公众号【OpenCV or Android】,热爱Android、Kotlin、Flutter和OpenCV。毕业于华中科技大学计算机专业,曾就职于华为武汉研究所。目前在三线小城市生活,专注技术与研发。
    转载请注明原文地址: https://ju.6miu.com/read-24585.html

    最新回复(0)