gpt4 book ai didi

android - 如何在 Android Studio 中比较两个 LiveData 是否相等?

转载 作者:行者123 更新时间:2023-12-04 15:19:48 28 4
gpt4 key购买 nike

我有两个 LiveDataaMVoice1aMVoice2

我希望检查它们是否相等。

我知道我需要使用 observe 来获取 LiveData 的值。

所以我认为 isEqual = (mDetailViewModel.aMVoice1.value==mDetailViewMode2.aMVoice1.value ) 是错误的。

但我认为 fun observeVoice() 存在一些问题,我该如何解决?

class FragmentDetail : Fragment() {

private lateinit var binding: LayoutDetailBinding

private val mDetailViewModel by lazy {
...
}

var isEqual=false

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
...
binding.lifecycleOwner = this.viewLifecycleOwner
binding.aDetailViewModel=mDetailViewModel

isEqual = (mDetailViewModel.aMVoice1.value==mDetailViewMode2.aMVoice1.value ) // I don't think it's correct.

observeVoice()
return binding.root
}

fun observeVoice() {
mDetailViewModel.aMVoice1.observe(viewLifecycleOwner){value1->
isEqual = (value1==mDetailViewModel.aMVoice2.value) // mDetailViewModel.aMVoice2.value maybe null
}
}

}


class DetailViewModel(private val mDBVoiceRepository: DBVoiceRepository, private val voiceId1:Int,private val voiceId2:Int) : ViewModel() {
val aMVoice1=mDBVoiceRepository.getVoiceById(voiceId1)
val aMVoice2=mDBVoiceRepository.getVoiceById(voiceId2)
}

class DBVoiceRepository private constructor(private val mDBVoiceDao: DBVoiceDao){
fun getVoiceById(id:Int)=mDBVoiceDao.getVoiceById(id)
}


@Dao
interface DBVoiceDao{
@Query("SELECT * FROM voice_table where id=:id")
fun getVoiceById(id:Int):LiveData<MVoice>
}

data class MVoice(
@PrimaryKey (autoGenerate = true) @ColumnInfo(name = "id") var id: Int = 0,
var name: String = "",
var path: String = ""
)

添加的内容

下面的代码可以吗?

fun observeVoice() {
mDetailViewModel.aMVoice1.observe(viewLifecycleOwner){value1->
mDetailViewModel.aMVoice2.observe(viewLifecycleOwner){value2->
isEqual = (value1==value2)
}
}
}

最佳答案

据官方documents ,实现此类情况的解决方案的最佳方法是使用 MediatorLiveData 作为 LiveData 合并。使用它,您可以在将新值发布到任一 LiveData 时检查值的相等性:

class DetailViewModel(...) : ViewModel() {

val areMVoicesEqual = MediatorLiveData<Boolean>().apply {
addSource(aMVoice1) { postValue(it == aMVoice2.value) }
addSource(aMVoice2) { postValue(it == aMVoice1.value) }
}
}

然后:

fun observeVoice() {
mDetailViewModel.areMVoicesEqual.observe(viewLifecycleOwner){ equality ->
// do whatever you want with `equality`
}
}

请注意,您提到的Added Content fragment 不正确。事实上,在这种情况下,每次在 aMVoice1 上观察到一个值时,都会有一个新的 Observer 开始在 aMVoice2 上观察,这是不对的.

关于android - 如何在 Android Studio 中比较两个 LiveData 是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63558350/

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