miqbaldc
11/22/2021, 6:41 AM.collect
-in flows inside .collect
works this ways?
Would love to know if there’s any suggestion/feedback to improve below snippet code ❤️
lifecycleScope.launchWhenCreated {
val uploadsBody = mutableListOf<File>()
files
.asFlow()
.map { originalFile ->
originalFile
.compressImageAsFlow(this)
.collect { compressedImageFile ->
uploadsBody.add(compressedImageFile)
}
uploads
}
.collect { result ->
viewModel.uploadFile(this, result)
}
}
bezrukov
11/22/2021, 2:21 PMsuspend fun compressImage
instead
2. currently processing multiple files (e.g. [A, B, C]) you will end up with calling viewModel.uploadFile multiple times [A], [A, B], [A, B, C]. I don't think it is what you want
3. do not build list manually (maintaining mutableList), use terminal operator toList()
to summarize:
val compressedFiles = files
.asFlow
.map { originalFile -> originalFile.compressImage(..) }
.toList()
viewModel.uploadFiles(this, compressedFiles)
I also not sure you need to use flow here, most likely list/sequence (depending on files
type) is enough for this examplemiqbaldc
11/22/2021, 4:00 PMFlow
because comporessImageAsFlow
using a callbackFlow
(an external API). Didn’t realize that it’s possible to use suspend
, might needs to works a little bit to refactor. 🙏miqbaldc
11/22/2021, 4:15 PMsuspend
-> for single value
Flow<T>
-> for collections
cmiiw(?)bezrukov
11/22/2021, 5:29 PMsuspendCancellableCoroutine
to turn an external API to suspend funNick Allen
11/22/2021, 5:59 PMf(): T
-> for single value available/compuatable now (don't use coroutines when you don't need to)
suspend f(): T
-> for single value available later
suspend f(): List<T>
-> for collection that is available all at once after a bit (like a network request that returns a list)
f(): Flow<T>
-> for collection where items arrive over time (like listening for DB changes)miqbaldc
11/23/2021, 2:41 AMThanks for this part. We excessively trying-> for collection that is available all at once after a bit (like a network request that returns a list)suspend f(): List<T>
f(): Flow<List<T>>
in our codebase until now for our network request.
Does the f(): Flow<T>
for network request a recommended to use? e.g: we try to listening for RecyclerView/list updates for pagination cmiiw