我有一个列表,当我触摸一个项目时,我希望下载与该项目相关的文件。我编写了下载文件的代码,但我有一个问题。用户可能同时触摸几个项目,并希望同时下载它们。我的代码的问题是,当我同时触摸几个项目时,下载操作相互干扰。
ViewModel类:
class BusinessViewModel(private val userRepository: UserRepository) : ViewModel() {
val downloadSqliteDatabaseData: MutableState<State<String>> = mutableStateOf(State.Empty)
fun downloadSqliteDatabase(file: File?, businessId: Long) {
viewModelScope.launch {
userRepository.downloadSqliteDatabase(businessId).onStart {
downloadSqliteDatabaseData.value = State.Loading
}.catch {
downloadSqliteDatabaseData.value = State.Error("ERROR", MyHttpStatusCode.NetworkError)
}.collect {
downloadSqliteDatabaseData.value = when (it.status) {
HttpStatusCode.OK -> {
try {
val data: ByteArray = it.body()
file?.writeBytes(data)
State.Success("", it.status)
} catch (ex: Exception) {
State.Error("ERROR", MyHttpStatusCode.ConvertDataError)
}
}
MyHttpStatusCode.InvalidUser -> {
State.Error("ERROR", it.status)
}
else -> {
State.Error("ERROR", it.status)
}
}
}
}
}
}
字符串
合成功能:
val downloadSqliteDatabaseData by remember { viewModel.downloadSqliteDatabaseData }
DisposableEffect(downloadSqliteDatabaseData) {
when (downloadSqliteDatabaseData) {
is State.Empty -> {}
is State.Loading -> {
//downloadDatabaseLoading.value = true
}
is State.Success -> {
//downloadDatabaseLoading.value = false
}
is State.Error -> {
println("Error")
//downloadDatabaseLoading.value = false
}
}
onDispose {
}
}
LazyColumn(
state = lazyListState,
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
itemsIndexed(
items = businessList,
key = { _, item -> item.id },
) { index, item ->
ClickBox(
modifier = Modifier
.padding(start = 15.dp, end = 15.dp)
.fillMaxWidth()
.height(120.dp),
onClick = {
val dbPath = File("test.txt")
viewModel.downloadSqliteDatabase(dbPath, item.id)
}
) {
//....
}
}
}
型
1条答案
按热度按时间44u64gxh1#
你使当前文件的下载成为整个UI状态的焦点。
字符串
如果要处理多个,则需要向下传递到列表中项目的状态。
型
下面是工作示例的其余部分
型