有趣的流程,转换为实时数据时为null

问题描述 投票:0回答:1

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

我的阅读编号为空,但是有任何想法吗?

android kotlin android-livedata kotlin-flow
1个回答
0
投票

这是因为您试图直接将glucoseFlow.value分配给_glucoseFlow.value,我想您应该使用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)。

© www.soinside.com 2019 - 2024. All rights reserved.