dan*_*ela 5 android mvvm kotlin android-livedata
For example, let's say that we have a product catalog view with an option to add product to a cart. Each time when user clicks add to cart, a viewModel method addToCart is called, that could look like this:
//inside viewModel
fun addToCart(item:Item): LiveData<Result> = liveData {
val result = repository.addToCart(item) // loadUser is a suspend function.
emit(result)
}
//inside view
addButton.onClickListener = {
viewModel.addToCart(selectedItem).observe (viewLifecycleOwner, Observer () {
result -> //show result
}
}
Run Code Online (Sandbox Code Playgroud)
What happens after adding for example, 5 items -> will there be 5 livedata objects in memory observed by the view?
If yes, when will they be cleanup? And if yes, should we avoid livedata builder for one-shot operations that can be called multiple times?
您的实施似乎是错误的!LiveData
您不断地为每个addToCard
函数调用返回一个新对象。关于你的第一个问题,这是一个Yes
.
如果你想通过 liveData 正确地做到这一点。
// In ViewModel
private val _result = MutableLiveData<Result>()
val result: LiveData<Result>
get() = _result;
fun addToCart(item: Item) {
viewModelScope.launch {
// Call suspend functions
result.value = ...
}
}
// Activity/Fragment
viewModel.result.observe(lifecycleOwner) { result ->
// Process the result
...
}
viewModel.addToCart(selectedItem)
Run Code Online (Sandbox Code Playgroud)
您所要做的就是从活动中调用它并处理结果。您也可以用于StateFlow
此目的。它还有一个扩展asLiveData
,可以转换 Flow -> LiveData。
归档时间: |
|
查看次数: |
1171 次 |
最近记录: |