I have a Home Fragment, and inside thatonCreateView
fragment, I have 2 function, that will execute lifecycleScope
.
The first lifecycleScope
will used to get all the list of cashFlow
, and the second lifecycleScope
will use to get all the total of outcome
and income
.
Here is the onCreateView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val content = inflater.inflate(R.layout.fragment_home, container, false) as ConstraintLayout
btnNewOutcome(content)
btnNewIncome(content)
val cashFlowDao = (activity?.applicationContext as CashFlowApp).db.cashFlowDao()
loadCashFlow(cashFlowDao, content)
loadTotalTransaction(cashFlowDao, content)
return content
}
This is the first lifecycleScope
that will used to get all the cashFlow
history,
private fun loadCashFlow(cashFlowDao: CashFlowDao, content: View) {
lifecycleScope.launch {
cashFlowDao.fetchAllCashFlow().collect {
val cashFlowList = ArrayList(it)
setupHistoryCashFlow(cashFlowList, cashFlowDao, content)
}
}
}
This is the second lifecycleScope
that will used to get the total of cashFlow
,
private fun loadTotalTransaction(cashFlowDao: CashFlowDao, content: View) {
lifecycleScope.launch {
val totalIncome: Int = cashFlowDao.calculateIncome(Constant.INCOME)
val totalOutcome: Int = cashFlowDao.calculateIncome(Constant.OUTCOME)
Log.e("Total", totalIncome.toString())
setupTotalTransaction(totalIncome, totalOutcome, content)
}
}
When trying to run the application, it will crash with this error message.
You can find the repository on this link, and pay attention on HomeFragment
and MainActivity
https://github.com/gandarain/money_track_app
CodePudding user response:
I suspect the function calculateIncome()
is not suspend
, and it is blocking the current thread (Main Thread).
Marking calculateIncome()
function as suspend
in CashFlowDao
should solve the problem. It will not block the Main Thread.
In CashFlowDao
class:
suspend fun calculateIncome(...): Int