'Fun with flows, getting null when converting to live data

I am trying out flows and trying to see how they can be converted to mvvm with android view models. Here is what I tried first to test it out :

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()
    }
}

I get a null for the reading number however any ideas ?



Solution 1:[1]

If you are using databinding, do not forget specify the fragment view as the lifecycle owner of the binding so that the binding can observe LiveData updates.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yeatom Liu