Home > Software engineering >  Why not auto update list when used LiveData in Android
Why not auto update list when used LiveData in Android

Time:04-07

In my application I want use Koin , Room and LiveData.
I write below codes, but after add new item into room not auto update recyclerview list!
Should close app and open again for show updated list !

Dao codes :

@Query("SELECT * FROM $NOTE_TABLE")
fun getAllNote(): MutableList<NoteModel>

Repository codes :

class RoomRepository(private val dao: NoteDao) {

    suspend fun saveNote(note: NoteModel) = dao.saveNote(note)
    fun getAllNotes() = dao.getAllNote()

}

ViewModel codes:

class RoomViewModel(private val repository: RoomRepository) : ViewModel() {

    val notesList = MutableLiveData<MutableList<NoteModel>>()

    fun saveNote(note:NoteModel) = viewModelScope.launch {
        repository.saveNote(note)
    }

    fun loadAllNotes() = viewModelScope.launch {
        val list = repository.getAllNotes()
        if (list.isNotEmpty()) {
            notesList.postValue(list)
        }
    }
}

Activity codes :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityKoinRoomBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //InitViews
        binding.apply {
            //Save
            btnSave.setOnClickListener {
                val title = titleEdt.text.toString()
                note.id = 0
                note.title = title
                viewModel.saveNote(note)
            }
            //Load notes
            viewModel.loadAllNotes()
            viewModel.notesList.observe(this@KoinRoomActivity) {
                noteAdapter.differ.submitList(it)

                notesList.apply {
                    layoutManager = LinearLayoutManager(this@KoinRoomActivity)
                    adapter = noteAdapter
                }
            }
        }

How can I fix this issue?

CodePudding user response:

In order to update data immediately, you need to return LiveData<T> from the database itself. In your case, do something like that:

@Query("SELECT * FROM $NOTE_TABLE")
fun getAllNote(): LiveData<List<NoteModel>>

I also changed MutableList to List, because there is no need for mutability here.

You ViewModel can then be like this:

class RoomViewModel(private val repository: RoomRepository) : ViewModel() {

    val notesList = repository.getAllNotes()

    ...
}

and you can also remove function loadAllNotes() from it.

CodePudding user response:

Try changing the return type in the DAO and observe it from the activity. Then, add it to the recyclerview adaper

Change this

fun getAllNote(): MutableList<NoteModel>

to

fun getAllNote(): LiveData<List<NoteModel>>
  • Related