本文介绍了从服务类写入领域导致UI阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在每个位置更改侦听器上从LocationService类编写领域db,并在Activity中列出此更改以更新UI.最初它可以正常工作,但是当领域db中的条目数超过2K时,它开始阻止UI.任何人都可以建议.

I am writing realm db from my LocationService class on every location change listener and listing this change in Activity to update the UI. Initially it works fine, however when number of entries in realm db exceeds 2K, it is started blocking the UI. Anyone please suggest.

推荐答案

是的,问题在于Service在MainThread中运行(默认情况下为UI线程).您需要在后台线程上异步写入数据.注意,Realm实例是线程相关的,并且必须在单个写入事务中阻塞它并释放它.考虑使用IntentService-默认情况下具有后台线程,或者使用rxJava库组织后台作业-这是最简单的方法.这是一个如何完成的代码:

Yes, the problem is that Service run in MainThread (UI thread by default). you need to write data asynchronously on background thread. Notice, that Realm instance is thread dependent and it has to be obrained and released in single write transaction. Consider using IntentService - it has background thread by default, or, use rxJava library for organizing background job - it's the simplest way. Here is a code how it can be done:

PublishSubject<Location> locationSource = PublishSubject.create();

        // bind to location source for receiving locations
        Observable<Integer> saveToDbTask =
        locationSource.asObservable()
                // this line switches execution into background thread from embedded thread pool
                .observeOn(Schedulers.computation())
                .map(location -> {
                    int result -> saveLocationToDb(location);
                    return result;
                });

        // subscribe to that task when you start
        Subscription subscription = saveToDbTask.subscribe(t -> {
            Log.i(LOG_TAG, "Result: " + t);
        });

        // unsubscribe when it is no longer needed
        if (null != subscription && !subscription.isUnsubscribed()){
            subscription.unsubscribe();
            subscription = null;
        }

        // tunnel location from your FusedLocationApi's callback to pipeline:
        Location loc = new Location(..);
        locationSource.onNext(loc);

这篇关于从服务类写入领域导致UI阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 03:19