0

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. enter image description here

You can find the repository on this link, and pay attention on HomeFragment and MainActivity https://github.com/gandarain/money_track_app

Sergio
  • 27,326
  • 8
  • 128
  • 149
Ganda Rain Panjaitan
  • 833
  • 1
  • 12
  • 28

1 Answers1

1

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
Sergio
  • 27,326
  • 8
  • 128
  • 149
  • Thanks, it works, but I was wonder. I have other function on CashFlowDao, fetchAllCashFlow, i did not put suspend on that function, but it still working fine. For this calculateOutcome i did not put suspend, and it retun error. Do you know why? – Ganda Rain Panjaitan May 02 '22 at 09:54
  • Dao functions that return `Flow` are calculated lazily without blocking the current thread, they start execution when consumer consumes it by calling one of the terminal operators, like `collect` in your case. – Sergio May 02 '22 at 10:04