Tushar
08/14/2024, 7:33 PMRemoteDataSource
which takes two api one for fetching books another is google books api for additional metadata
questions
1. I am currently using Retrofit to download ebooks and save them into the filesDir
of my app should remoteDataSource handle saving files locally. Here’s a snippet of the code I use to save the file
private fun ResponseBody.saveFile(fileName: String): Flow<InternalDownloadState> {
return flow{
emit(InternalDownloadState.Downloading(0))
val destinationFile = File(context.filesDir,fileName)
try {
byteStream().use { inputStream->
destinationFile.outputStream().use { outputStream->
val totalBytes = contentLength()
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var progressBytes = 0L
var bytes = inputStream.read(buffer)
while (bytes >= 0) {
outputStream.write(buffer, 0, bytes)
progressBytes += bytes
bytes = inputStream.read(buffer)
emit(InternalDownloadState.Downloading(((progressBytes * 100) / totalBytes).toInt()))
}
}
}
emit(InternalDownloadState.Finished("file://${destinationFile.absolutePath}"))
} catch (e: Exception) {
emit(InternalDownloadState.Failed(e))
}
}
.flowOn(<http://Dispatchers.IO|Dispatchers.IO>).distinctUntilChanged()
}
2. Currently in my datasource
class i am fetching the list of books from my first api and calling google books api for every book to get additional metadata is it the right way to let datasource
handle this merging operation? moreover using repositories for merging seems counter-intuitive as calling the different function of same datasource
again to get the complete data when this could be handled internally by datasource
itself (edited)