Kotlin Coroutines For Async Functions in Android

in GitPlait4 years ago (edited)

Project Thunder Guava

Disclaimer: If you don't think the snippets or logic is right, or if you have a better idea, please be respectful and comment down your thoughts and concerns. I'm not an expert Android Dev, I only do it as a hobby.

Before June ended, I started working again with a Simple Wallet for Android I called Project ThunderGuava with an aim of learning and producing an output.

Simple UI

My design style is straightforward and minimalistic. I want clickable items to be reachable by my thumb when using my smartphone.

I have been using DesignMgr, an XML-less UI element generator at runtime to create my app UI.

Heavy Processes

I have always dreaded Kontlin Coroutines, just by looking at it, I feel that I can't do it.

But working with ThunderGuava, I was forced to learn coroutines.

Unlike interpreted programming languages, running Kotlin/Android apps will take time to build before installing and running, so learning new features is a challenge—you just don't know if it'll crash or break, what's sure is that it won't be working.

Parsing large text-based files will surely slow down your smartphone and the UI might encounter hangs or crash.

Asynchronous processes is a solution by running processes on a new thread.

A sample scenario is having your own butler/worker, and he will do certain tasks for you so you can continue with other things. He can prepare your meals, wash dishes, clean your house, and buy grocery while you do other things.

If you, alone, do everything at once, it's hard to complete all of it when all are urgent and important, you end up doing nothing or even get exhausted—that is a hang or crash.

Technical Terms

You can add suspend to your util fuctions to allow the asynchronous logic then wrap your function code with withContext and set Dispatchers depending on your needs.

private fun updateIfFound() {
    // Dispatchers.Main is for lighter jobs
    CoroutineScope(Dispatchers.Main).launch {
        val check = doThis()
        // update UI here
    }
}
private suspend fun doThis(path: String): Boolean {
    // Diispatchers.Default for heavy jobs, such as reading large about of DB contents, parsing large JSON/XML data, reading large files, waiting for HTTP requests, etc.
    return withContext(Dispathers.Default) {
       val data = FileMgr(path).parse().get("key")
       return@withContext data.isNotEmpty()
    }
}

You can also blocking coroutines, by waiting for the job to be done.

private fun getKeyCount() {
    // Dispatchers.Main is for lighter jobs
    CoroutineScope(Dispatchers.Main).launch {
        val jobForCount = async { countKeys() }
        val count = jobForCount.await()
        // update UI here
    }
}
private suspend fun countKeys(path: String): Int {
    // Diispatchers.Default for heavy jobs, such as reading large about of DB contents, parsing large JSON/XML data, reading large files, waiting for HTTP requests, etc.
    return withContext(Dispathers.Default) {
       return@withContext FileMgr(path).parse().countUniqueRows()
    }
}

Working with Project ThunderGuava taught me to learn something I dread or I was afraid to even read about.

To grow as a software developer, you must learn to embrace challenges and conquer it.

Most of the times, it's just difficult at the beginning, as time goes, it becomes more easier to use.

Transaction Summary

Here's the top part of ThunderGuava's UI, it shows the live date and summary for the whole year's income, expenses, and net value.

Below the summary will list all the transactions per month, clicking on the Month header will show a HorizontalScroller of the list of months from January to the current month, then selecting it will update list with the selected month.

Handling thousands of rows and doing complex calculations with custom conditins will really need coroutines, or the app will hang up.

For the data I'm collecting/using refer to Fixing Custom DateTime Formats into Unix Time in Python for reference.

DIY Bottom Bar

This is not yet the final UI and will include more elements to show settings and other features.

This is an ongoing project, a pocket-sized financial assistant, currently I'm working again to make it into fruition before the year ends. Just simple libs, lightweight UI, and straighforward features.

Project ThunderGuava
Android • Kotlin • SQlite

Guava icon made by ultimatearm from Flaticons
Banner images from FreePngImg site

#CodeRunDebug


Curious about Crypto?
Buy and Sell on Coinbase
Get Started


About Me

@oniemaniego is a test engineer, but outside work, he experiments in the kitchen, writes poetry and fiction, paints his heart out, or toils under the hot sun.

Onie Maniego was born in Leyte, PH. He grew up in a rural area with a close-knit community and a simple lifestyle, he is often visiting his father's orchards during summer and weekends, which has a great impact on his works.

Don't forget to vote, comment, and follow me.


Not yet on Hive? Earn while blogging.
Sign Up

Sort:  

Congratulations @oniemaniego! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You distributed more than 200 upvotes. Your next target is to reach 300 upvotes.

You can view your badges on your board And compare to others on the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

We do really appreciate posting through our community. Cool work you got there. I feel you could work more on the UI. Thanks for sharing 😊👍

Your post has been submitted to be manually curated by @gitplait community account because this is the kind of publications we like to see in our community.

Join our Community on Hive and Chat with us on Discord.

[Gitplait-Team]

Thanks! I'll improve the UI once the functionality is Ok-ish, for now that's just a "placeholder" design 😆

@oniemaniego, thank you for supporting the HiveBuzz project by voting for @steemitboard as a witness.

Here Is a small present to show our gratitude
Click on the badge to view your Board of Honor.

Once again, thanks for your support!

Yay! You're welcome @hivebuzz 🐝

Thank you for your unfailing support @oniemaniego, really appreciated! 🙏❤️