当前位置: 首页 > 知识库问答 >
问题:

LiveData可以使用recyle视图,但MutableLiveData不可以。为什么?

詹夕
2023-03-14
@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)
    }

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


}
    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()
        }
    }
    null

[编辑]

带有MutableLiveData的模型视图

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


}

共有1个答案

南宫才英
2023-03-14

尝试mediatorlivedata而不是mutable

存储库:

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

模型视图

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
       }
    }
 类似资料:
  • 我使用在之间切换,但是我可以使用在简单XML布局之间切换吗? 这是ViewPager的页面,用于在片段之间滑动: 这是我的提示片段: 如何修改代码以使用视图而不是片段?

  • 本文向大家介绍为什么说cookie不可以滥用?相关面试题,主要包含被问及为什么说cookie不可以滥用?时的应答技巧和注意事项,需要的朋友参考一下 1.安全问题 2.每次请求都会携带cookie,占内存,影响带宽 3.不能跨域 4.可储存的内容少

  • 本文向大家介绍为什么MySQL 使用timestamp可以无视时区问题.,包括了为什么MySQL 使用timestamp可以无视时区问题.的使用技巧和注意事项,需要的朋友参考一下 之前一直有过疑惑为什么MySQL数据库存timestamp可以无视时区问题. 在业务中也是一直使用Laravel框架,内置的Migration也是使用的timestamp类型字段, 也没太关心. 开始 查看当前数据库时区

  • 问题内容: 根据MySQL性能Wiki的提示: 拥有或可以使用GROUP BY时,请勿使用DISTINCT。 有人可以发布可以使用GROUP BY代替DISTINCT的查询示例吗? 问题答案: 如果您知道结果中的两列始终直接相关,那么这样做会比较慢: 比这个: 因为在第二种情况下,它只需要比较ID,但是在第一种情况下,它必须比较两个字段。这是MySQL特有的技巧。它不能与其他数据库一起使用。

  • 问题内容: 为什么可以,但不能编译? 问题答案: 常量被评估为int,因此会溢出并为您提供一个新的int,该int可分配给,同时也被评估为equals ,而不能分配给。