Vid Vid - 16 days ago 5
Java Question

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.

Answer

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