Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MainActivity : AppCompatActivity() {
val textview by lazy { findViewById<View>(R.id.textView) as TextView }
val progressBar by lazy { findViewById<View>(R.id.progressbar) as ProgressBar }
val buttonMusic by lazy { findViewById<View>(R.id.button_music) as Button }
var progressPercentage = 0
private var job: Job? = null
val scope by lazy { CoroutineScope(Dispatchers.Main) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("activity", "OnCreate")
buttonMusic.setOnClickListener {
startDownloading("Music", 200)
}
}
private fun startDownloading(item: String, delay: Long) {
job = scope.launch {
textview.text = "Downloading..."
delay(300)
while (progressPercentage != 100) {
delay(delay)
progressPercentage++
textview.text = "Percentage...$progressPercentage"
progressBar.setProgress(progressPercentage)
logCoroutineInfo("$item | perc $progressPercentage")
}
textview.text = "$item Downloaded ✅"
}
}
fun logCoroutineInfo(msg: String) = println("Running on: [${Thread.currentThread().name}] | $msg")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment