Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

java - Writing realm from service class causing UI block

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...