无法观察流作为LiveData。

huangapple go评论64阅读模式
英文:

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&lt;Int&gt;
{
    return flow {
        emit(number)
    }
}

fun setNumber(l: Int)
{
    number = l
}

ViewModel (mainVM):

fun readNumber(): LiveData&lt;Int&gt;
{
    return repo.readNumber().asLiveData(viewModelScope.coroutineContext)
}

fun setNumber(l:Int)
{
    repo.setNumber(l)
}

Fragment:

     mainVM.readNumber().observe(this){
        Log.i(&quot;DEBUGER&quot;, &quot;number: ${it}&quot;)
    }

    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 }

huangapple
  • 本文由 发表于 2023年6月16日 15:10:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76487741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定