Skip to content

Instantly share code, notes, and snippets.

@Shivamdhuria
Last active February 14, 2022 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shivamdhuria/0050da3b4c6e9a3560d98170ded6a986 to your computer and use it in GitHub Desktop.
Save Shivamdhuria/0050da3b4c6e9a3560d98170ded6a986 to your computer and use it in GitHub Desktop.
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