У меня есть ArrayList файлов. Я хочу удалить их в фоновом потоке, используя kotlin сопрограмм и обновить пользовательский интерфейс. Эта функция работает в MainActivity. Я использовал LifeCycleScope для запуска сопрограмм в MainActivity
Это функция:
private fun deleteFiles(arrayList: ArrayList<File>) {
val progressTextView = findViewById<TextView>(R.id.progressTextView)
val length = arrayList.size
lifecycleScope.launch {
withContext(IO){
for(it in 0 until arrayList.size) {
try {
arrayList[it].delete()
if(arrayList[it].exists()) {
arrayList[it].canonicalFile.delete()
if(arrayList[it].exists()) {
deleteFile(arrayList[it].name)
}
}
} catch(e: java.lang.Exception) {
Log.d("Exception", "$e")
}
withContext(Main){
val progressPercentage = ((it + 1).toDouble() / length.toDouble()) * 100 // math to calculate the percentage of files deleted
progressTextView.text = "$progressPercentage %" // update progress in textView
}
}
}
}
}
Должен ли я использовать WorkManager API для этого? Есть ли лучший подход к этому?