为什么在我使用了 LiveData 后还需要启动 notifyDataSetChanged()?

Hel*_*oCW 1 android kotlin android-livedata android-jetpack

我正在通过https://github.com/googlecodelabs/android-room-with-a-view/tree/kotlin的示例项目 RoomWordsSample 学习 Room

以下代码来自项目。

在我看来,如果观察到数据发生变化,LiveDate 将自动更新 UI。

但是在文件 WordListAdapter.kt 中,我发现notifyDataSetChanged()添加到function setWords(words: List<Word>)? 似乎它必须在数据更改时手动通知 UI。

为什么还需要启动 notifyDataSetChanged()当我使用 LiveData 时,?

主活动.kt

class MainActivity : AppCompatActivity() {

    private val newWordActivityRequestCode = 1
    private lateinit var wordViewModel: WordViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
        val adapter = WordListAdapter(this)
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this)

        wordViewModel = ViewModelProvider(this).get(WordViewModel::class.java)


        wordViewModel.allWords.observe(this, Observer { words ->         
            words?.let { adapter.setWords(it) }
        })

    }
}
Run Code Online (Sandbox Code Playgroud)

WordViewModel.kt

class WordViewModel(application: Application) : AndroidViewModel(application) {

    private val repository: WordRepository 
    val allWords: LiveData<List<Word>>

    init {

        val wordsDao = WordRoomDatabase.getDatabase(application, viewModelScope).wordDao()
        repository = WordRepository(wordsDao)
        allWords = repository.allWords
    }


    fun insert(word: Word) = viewModelScope.launch {
        repository.insert(word)
    }
}
Run Code Online (Sandbox Code Playgroud)

词表适配器.kt

class WordListAdapter internal constructor(
        context: Context
) : RecyclerView.Adapter<WordListAdapter.WordViewHolder>() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)
    private var words = emptyList<Word>() // Cached copy of words

    inner class WordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val wordItemView: TextView = itemView.findViewById(R.id.textView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WordViewHolder {
        val itemView = inflater.inflate(R.layout.recyclerview_item, parent, false)
        return WordViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: WordViewHolder, position: Int) {
        val current = words[position]
        holder.wordItemView.text = current.word
    }

    internal fun setWords(words: List<Word>) {
        this.words = words
        notifyDataSetChanged()
    }

    override fun getItemCount() = words.size
}
Run Code Online (Sandbox Code Playgroud)

Abd*_*iaz 5

实际上,livedata会在您的活动中为您提供更新的数据。但是现在,更新 ui 是您的 Activity 的工作。因此,每当实时数据为您提供更新的数据时,您都必须告诉 ui 更新数据。因此,notifyDataSetChanged()