🛠️ Optimize loading in Browse

* Sped up loading in Browse using coroutines

Part-of: #91
This commit is contained in:
Acclorite 2025-01-17 14:38:49 +02:00
parent cf7e85c267
commit 7dd1a496de

View file

@ -7,6 +7,10 @@ import android.os.Environment
import android.os.storage.StorageManager import android.os.storage.StorageManager
import android.util.Log import android.util.Log
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import ua.acclorite.book_story.R import ua.acclorite.book_story.R
import ua.acclorite.book_story.data.local.room.BookDao import ua.acclorite.book_story.data.local.room.BookDao
@ -77,17 +81,28 @@ class FileSystemRepositoryImpl @Inject constructor(
/** /**
* Get all verified files from directory (root). * Get all verified files from directory (root).
*/ */
fun File.getFilesFromDirectory(): List<SelectableFile> { suspend fun File.getFilesFromDirectory(): List<SelectableFile> {
return walk().mapNotNull { return withContext(Dispatchers.IO) {
if (!it.isValid()) return@mapNotNull null val semaphore = Semaphore(5)
walk()
.map { file ->
async {
semaphore.withPermit {
if (!file.isValid()) return@async null
SelectableFile( SelectableFile(
name = it.name, name = file.name,
path = it.path, path = file.path,
size = it.length(), size = file.length(),
lastModified = it.lastModified(), lastModified = file.lastModified(),
selected = false selected = false
) )
}.toList() }
}
}
.toList()
.awaitAll()
.filterNotNull()
}
} }
/** /**
@ -133,7 +148,7 @@ class FileSystemRepositoryImpl @Inject constructor(
val files = mutableListOf<SelectableFile>() val files = mutableListOf<SelectableFile>()
for (volume in storageDirectories) { for (volume in storageDirectories) {
files.addAll(withContext(Dispatchers.IO) { volume.getFilesFromDirectory() }) files.addAll(volume.getFilesFromDirectory())
} }
Log.i(GET_FILES_FROM_DEVICE, "Successfully got all matching files.") Log.i(GET_FILES_FROM_DEVICE, "Successfully got all matching files.")