Skip to content
Advertisement

Is there a way to do a lot of computational work effectively in an Android app?

While building a To-do List app, I wanted to show users the statistics. To-do lists created by users are stored in the Room Database. In order to show statistics on how hard the user has achieved to-do, the number of to-do completions is calculated over the years, but the app is starting to stumble. Even the calculation process is using CoroutineScope(Dispatchers.Default). I feel that the app is slowing down because I use code like the following to calculate the values ​​in the array.

runBlocking {
    withContext(CoroutineScope(Dispatchers.Default).coroutineContext) {
        var total = 0

        val todoDao = MyDatabase.getInstance(mContext).getTodoDao()
        val todos = todoDao.getTodos()

        for (i in todos) {
            if (i.user_done) {
                total++
            }
        }
    }
}

findViewById(R.id.total).text = total.toString()

The code above is part of the statistic calculation process presented to the user. How can you do a lot of calculations more efficiently, for example, when the app is turned on, pre-calculating and re-calculating according to the user’s actions?

Advertisement

Answer

I don’t use Kotlin very much but runBlocking is a sure fire way to slow down the app if its blocking the main thread. If this is the case, Room has an option to force it to stay off the UI Thread, thus if something is ran on the UI thread it will throw an exception.

The other issue could be memory how big is val todos? if todos is a large amount of objects then you have them all in RAM(which can get out of hand fast). If so consider batching, by pulling a limited amount and offsetting to pull the next limit, thus you only and have limit amount of objects at any given time, and GC won’t hate you.

(edit) I hate to add a library to the answer but looking into RxJava for Kotlin could be a real game changer, when it comes to these issues, it has worked wonders for me.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement