-6ren">
gpt4 book ai didi

android - LiveData 适用于回收 View ,但 MutableLiveData 不适用。为什么?

转载 作者:行者123 更新时间:2023-11-29 22:45:54 25 4
gpt4 key购买 nike

场景是这样的:

道:

@Dao
interface TipDAO {
@Query("SELECT * FROM tip_table")
fun getAll(): LiveData<List<Tip>>

@Query("SELECT * FROM tip_table WHERE title LIKE :title")
fun findByName(title: String): Tip

@Query("SELECT * from tip_table ORDER BY title DESC")
fun getAlphabetizedTips(): LiveData<List<Tip>>

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(vararg tip: Tip)

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(vararg tips: Tip)

@Delete
suspend fun delete(tip: Tip)

@Query("DELETE FROM tip_table")
suspend fun deleteAll()

存储库:


class TipRepository (private val tipDAO: TipDAO){

// Room executes all queries on a separate thread.
// Observed LiveData will notify the observer when the data has changed.
val allTips: LiveData<List<Tip>> = tipDAO.getAll()

// The suspend modifier tells the compiler that this must be called from a
// coroutine or another suspend function.

suspend fun insert (tip: Tip){
tipDAO.insert(tip)
}

fun getAlphabetizedTips (): LiveData<List<Tip>> {
return tipDAO.getAlphabetizedTips()
}

suspend fun delete (tip: Tip) {
tipDAO.delete(tip)
}

模型 View

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

private val repository : TipRepository
val allTips: LiveData<List<Tip>>


init {
val tipDAO = TipRoomDatabase.getDatabase(application).tipDao()
repository = TipRepository(tipDAO)
allTips = repository.allTips
}

fun insert (tip: Tip) = viewModelScope.launch {
repository.insert(tip)
}

fun delete (tip: Tip) = viewModelScope.launch {
repository.delete(tip)
}

fun getAlphabetizedTips () {
//How I can query so I can see the change ????¿¿¿¿
}


}

Activity

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

val recyclerView: RecyclerView = findViewById (R.id.content)
val adapter = TipListAdapter(this)

recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.isNestedScrollingEnabled = false

tipViewModel = ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory(this.application))
.get(TipViewModel::class.java)

tipViewModel.allTips.observe(this,
Observer<List<Tip>> { tips ->
// Update the cached copy of the tips in the adapter.
tips?.let { adapter.setTips(tips)} //setTips notify the listener
})

val addButton: Button = findViewById(R.id.how_to_add_bt)
val delButton: Button = findViewById(R.id.how_to_delete_bt)
val sortButton: ImageButton = findViewById(R.id.how_to_sort_bt)
val searchBar: TextView = findViewById(R.id.how_to_search_bar)

addButton.setOnClickListener {
Toast.makeText(this,"ADD", Toast.LENGTH_SHORT).show()
intent = Intent(this, AddActivity::class.java)
startActivityForResult(intent, NEW_TIP_ACTIVITY_REQUEST_CODE)
}

delButton.setOnClickListener {
TipListAdapter.delete = !TipListAdapter.delete //changes a flag
}

sortButton.setOnClickListener {
tipViewModel.getAlphabetizedTips()
}
///more irrelevant code

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

if (NEW_TIP_ACTIVITY_REQUEST_CODE == requestCode && resultCode == RESULT_OK && data!= null) {
data.let{
val description: String = it.getStringExtra(AddActivity.DESCRIPTION)!!
val title: String = it.getStringExtra(AddActivity.TITLE)!!
val image: String = it.getStringExtra(AddActivity.IMAGE)!!
Toast.makeText(this, "You have created a tip succesfully",Toast.LENGTH_SHORT).show()
val tip = Tip (null,title, image, description)
tipViewModel.insert(tip)
}
} else {
Toast.makeText(this,"The tip was not uploaded correctly",Toast.LENGTH_SHORT).show()
}
}

情况是,当我在 Model 中为 allTips 使用 LiveData 时,它会正确显示到 RecycleView 中。但是如果我使用 MutableLiveData 它什么都不显示。我的目标是使用 MutableLiveData 执行查询,并通知观察者更改 recycleview 数据。我的问题是:

  • 在 View 模型中,如何为我进行的每个查询更改 LiveData allTips 的值?即:getAlphabetizedTips、getTip(title) 等
  • 为什么 MutableLiveData 不能像下面的代码 fragment 那样工作?

[编辑]

带有 MutableLiveData 的模型 View

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

private val repository : TipRepository
val allTips: MutableLiveData<List<Tip>>


init {
val tipDAO = TipRoomDatabase.getDatabase(application).tipDao()
repository = TipRepository(tipDAO)
allTips.value = repository.allTips.value
}

fun insert (tip: Tip) = viewModelScope.launch {
repository.insert(tip)
}

fun delete (tip: Tip) = viewModelScope.launch {
repository.delete(tip)
}

fun getAlphabetizedTips () {
//How I can query so I can see the change ????¿¿¿¿
allTips.post(respository.getAlphabetizedTips.value)
}


}

最佳答案

尝试使用 MediatorLiveData 而不是可变的

存储库:

class TipRepository (private val tipDAO: TipDAO){

// Room executes all queries on a separate thread.
// Observed LiveData will notify the observer when the data has changed.
val allTips: LiveData<List<Tip>> = tipDAO.getAll()

// The suspend modifier tells the compiler that this must be called from a
// coroutine or another suspend function.

suspend fun insert (tip: Tip){
tipDAO.insert(tip)
}

fun getAlphabetizedTips (): LiveData<List<Tip>> {
return tipDAO.getAlphabetizedTips()
}

suspend fun delete (tip: Tip) {
tipDAO.delete(tip)
}

模型 View

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

private val repository : TipRepository
val allTips = MediatorLiveData<List<Tip>()


init {
val tipDAO = TipRoomDatabase.getDatabase(application).tipDao()
repository = TipRepository(tipDAO)
allTips.addSource(repository.allTips){
this.allTips.value = it
}
}

关于android - LiveData 适用于回收 View ,但 MutableLiveData 不适用。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58513149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com