-1

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.

Vid
  • 1,012
  • 1
  • 14
  • 29
  • 2
    *Anyone please suggest.* ... Seems like you need to change your code ... – Selvin Nov 21 '16 at 10:18
  • ohh, thank you Selvin... instead of simply down vote, you should give me an idea if you know something. And I don't want to use IntentService for this. – Vid Nov 21 '16 at 10:22
  • 2
    Instead ranting you should rather provide your code ... most programmers are not using magic orbs, so without the code it is hard to say what is the problem ... – Selvin Nov 21 '16 at 10:24

1 Answers1

1

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);
Alex Shutov
  • 3,217
  • 2
  • 13
  • 11