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

Posted

技术标签:

【中文标题】流的乐趣,转换为实时数据时为空【英文标题】:Fun with flows, getting null when converting to live data 【发布时间】:2020-05-21 22:10:09 【问题描述】:

我正在尝试流程并尝试查看如何使用 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()
    

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

【问题讨论】:

“我的读数为空”对于您的问题来说信息不足。请添加您的预期行为,导致它失败的原因,并可能添加一个完整的测试来证明您的观点 【参考方案1】:

发生这种情况是因为您尝试将glucoseFlow.value 直接分配给_glucoseFlow.value,我想您应该使用MediatorLiveData&lt;Int&gt;,但这不是我的最终建议。

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

// 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 上实现之前的实现,从HomeFragment 开始观察您的公共glucoseFlow,您将能够接收非空序列值(1 和2)。

【讨论】:

【参考方案2】:

如果您使用数据绑定,请不要忘记将片段视图指定为绑定的生命周期所有者,以便绑定可以观察 LiveData 更新。

class HomeFragment : Fragment() 
    ...
    binding.lifecycleOwner = viewLifecycleOwner

【讨论】:

以上是关于流的乐趣,转换为实时数据时为空的主要内容,如果未能解决你的问题,请参考以下文章

为啥 Firebase 实时数据库的数据在控制台中显示为空?

播放列表文件用于HTTP实时流的使用

实时消息协议流的所有可能容器

我正在尝试将 firebase 实时数据库中的数据检索到我的 recyclerview 中,但数据显示为空

Firebase 实时数据库定价与查询

PortAudio 用于连续输入流的实时音频处理