为什么在 Android 中使用 LiveData 时不自动更新列表

Why not auto update list when used LiveData in Android

在我的应用程序中我想使用 Koin , RoomLiveData.
我写了下面的代码,但是在将新项目添加到房间后不会自动更新 recyclerview 列表!
应该关闭应用程序并再次打开以显示更新列表!

道代码:

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

存储库代码:

class RoomRepository(private val dao: NoteDao) {

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

}

ViewModel 代码:

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 代码:

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
                }
            }
        }

我该如何解决这个问题?

为了立即更新数据,您需要从数据库本身return LiveData<T>。在你的情况下,做这样的事情:

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

我也把MutableList改成了List,因为这里不需要可变性

ViewModel可以这样:

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

    val notesList = repository.getAllNotes()

    ...
}

您还可以从中删除函数 loadAllNotes()