https://kotlinlang.org logo
#android
Title
# android
a

Ayden

09/28/2020, 3:57 PM
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

coroutinedispatcher

09/28/2020, 3:58 PM
Which result? Can you be more specific?
a

Anshulupadhyay03

09/28/2020, 3:59 PM
what are you doing with getVote() what does it do inside?
a

Ayden

09/28/2020, 4:03 PM
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

dawidhyzy

09/29/2020, 5:39 AM
n

Nikola Minoski

10/01/2020, 11:20 AM
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