Search code examples
androidkotlinandroid-roomrx-androidrx-kotlin

Reusing or recreating an observer?


I'm using a custom repository to get observables for data in a room database, e.g:

fun getUsers(): Observable<List<User>> = userDao.getAll()
        .toObservable()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnError { Logger.error(tag, "error getting users: ${it.message}") }
        .doOnNext { Logger.debug(tag, "fetched ${it.size} users") }

In my UI (Fragment) I start the subscription in onResume:

override fun onResume() {
        super.onResume()
        userObserver = repository.getUsers()
            .subscribe {
                // handle user
            }
    }

And in the onPause I have:

override fun onPause() {
        super.onPause()
        userObserver.dispose()
    }

Since each time repository.getUsers() is called, I'm creating a new Observable-object. Could this lead to memory leaks and should I rather try to reuse the observer instead of disposing and recreating it?


Solution

  • I would hold this inside a ViewModel. When your fragment is recreated, it'll reuse the previous viewmodel. This will increase performance as it won't have to recreate your observer, and recall the database, it'll just use what was previously obtained.

    See here: Android ViewModel