android - 流的乐趣,转换为实时数据时为空
问题描述
我正在尝试流程并尝试查看如何使用 android 视图模型将它们转换为 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
,我想您应该使用 a MediatorLiveData<Int>
,但这不是我的最终建议。
如果您收集流项目然后将它们分配给您的私有变量,您可以解决它。
// 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)。
推荐阅读
- reactjs - 如何将自定义 CSS 添加到我的 React 组件并覆盖默认 CSS 值?
- python - 如何使用 if 语句根据相应的键访问字典中的值?
- r - 使用 R 从 Dropbox 导入 .asc 文件
- solr - 用于存储范围的 Solr 字段
- curl - 各种自制软件安装中的 cURL 错误
- javascript - 在 Svelte 中实现门户
- javascript - 反应原生 DOM
- c# - WinForms 图形绘图
- android - 将波纹效果设置为 RecyclerView CardView 项目,而无需双击项目操作
- python - 有没有一种很好的方法可以在 python 中处理非常大的 XML 文件?