英文:
Can't observe flow asLiveData
问题
我正在学习关于LiveData和Flow的内容,但我无法观察返回Flow.asLiveData值的LiveData函数(来自ViewModel的readNumber())。我是否犯了一些错误?
Repository(repo):
var number = 0
fun readNumber(): Flow<Int>
{
return flow {
emit(number)
}
}
fun setNumber(l: Int)
{
number = l
}
ViewModel(mainVM):
fun readNumber(): LiveData<Int>
{
return repo.readNumber().asLiveData(viewModelScope.coroutineContext)
}
fun setNumber(l:Int)
{
repo.setNumber(l)
}
Fragment:
mainVM.readNumber().observe(this){
Log.i("DEBUGER", "number: ${it}")
}
binding.addButton.setOnClickListener {
mainVM.setNumber(Random.nextInt(100))
}
英文:
I'm learning about LiveData and Flow and I can't observe LiveData function which returns Flow.asLiveData value (readNumber() from ViewModel). Am I making some mistake?
Repository (repo):
var number = 0
fun readNumber(): Flow<Int>
{
return flow {
emit(number)
}
}
fun setNumber(l: Int)
{
number = l
}
ViewModel (mainVM):
fun readNumber(): LiveData<Int>
{
return repo.readNumber().asLiveData(viewModelScope.coroutineContext)
}
fun setNumber(l:Int)
{
repo.setNumber(l)
}
Fragment:
mainVM.readNumber().observe(this){
Log.i("DEBUGER", "number: ${it}")
}
binding.addButton.setOnClickListener {
mainVM.setNumber(Random.nextInt(100))
}
答案1
得分: 0
你在setNumber()
函数内部没有发出新值。
在你的情况下,使用StateFlow。
var number = MutableStateFlow(0)
fun readNumber() = number.asStateFlow()
fun setNumber(l: Int) = number.update { l }
英文:
You are not emitting new value inside setNumber()
.
Use a StateFlow in your case
var number = MutableStateFlow(0)
fun readNumber() = number.asStateFlow()
fun setNumber(l:Int) = number.update { l }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论