gpt4 book ai didi

android - 流的乐趣,转换为实时数据时为空

转载 作者:行者123 更新时间:2023-12-04 23:59:57 25 4
gpt4 key购买 nike

我正在尝试流程并尝试查看如何使用 Android View 模型将它们转换为 mvvm。这是我首先尝试测试的内容:

class HomeViewModel : ViewModel() {

private lateinit var glucoseFlow: LiveData<Int>
var _glucoseFlow = MutableLiveData<Int>()


fun getGlucoseFlow() {
glucoseFlow = flowOf(1,2).asLiveData()
_glucoseFlow.value = glucoseFlow.value
}
}


class HomeFragment : Fragment() {

private lateinit var viewModel: HomeViewModel

override fun onCreateView (
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.home_fragment, container, false)
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)

viewModel._glucoseFlow.observe(this, Observer {
handleUpdate(it)
})

viewModel.getGlucoseFlow()
}

private fun handleUpdate(reading : Int) {
glucose_reading.text = reading.toString()
}
}

我的阅读数为空,但有什么想法吗?

最佳答案

发生这种情况是因为您试图分配 glucoseFlow.value_glucoseFlow.value直接,我想你应该使用 MediatorLiveData<Int> ,但这不是我的最终建议。

如果你收集流项,然后将它们分配给你的私有(private)变量,你就可以解决它。

// For private variables, prefer use underscore prefix, as well MutableLiveData for assignable values.
private val _glucoseFlow = MutableLiveData<Int>()
// For public variables, prefer use LiveData just to read values.
val glucoseFlow: LiveData<Int> get() = _glucoseFlow

fun getGlucoseFlow() {
viewModelScope.launch {
flowOf(1, 2)
.collect {
_glucoseFlow.value = it
}
}
}

HomeViewModel 之前实现,开始观察你的公众glucoseFlow来自 HomeFragment并且您将能够接收非空序列值(1 和 2)。

关于android - 流的乐趣,转换为实时数据时为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60085216/

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