• 7
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

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?

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

  • 1
Reply Report