Hi guys. I have the following code below, why my c...
# android
a
Hi guys. I have the following code below, why my chart result always render before
LiveData
?
Copy code
private fun getVoteData(): ArrayList<PieEntry> {
    ...
    val viewModel = ViewModelProvider(this, voteViewModelFactory).get(VoteViewModel::class.java)
    val liveData = viewModel.getVote()
    liveData.observe(viewLifecycleOwner, { vote ->
        vote.forEach {
            votes.add(PieEntry(it.total.toFloat(), it.name))
        }
    })
    return votes
}

private fun generateChart(binding: FragmentPieChartBinding, getVoteData: ArrayList<PieEntry>) {
    ...

    // Run before livedata execute
    Log.d("TEST", votes.toString())

    ...
    // Render chart result
}
stackoverflow 4
c
Which result? Can you be more specific?
a
what are you doing with getVote() what does it do inside?
a
I want to render a chart based on the data retrieve from
getVoteData()
function.
But now my chart always render before getVoteData return the value.
d
n
consider using MediatorLiveData like:
Copy code
val votesMediator = MediatorLiveData<..>()
votesMediator.addSource(viewModel.getVote()) {votes ->
    votesMediator.psotValue(votes.map { PieEntry(it.total.toFloat(), it.name) })
}
and do votesMediator.observe(.. in fragment/activity onCreate or use votesMediator with data-binding