Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

71%
+3 −0
Q&A Pipeline for zipping multiple file chanel into a single output channel

Well, ain't this fun hehe Turns out I failed to see .reader launches its own job, which resulted in multiple coroutines contending for the zip stream, each trying to write an entry... 🤦 The solut...

posted 1y ago by tmpod‭

Answer
#1: Initial revision by user avatar tmpod‭ · 2023-09-12T00:30:55Z (about 1 year ago)
Well, ain't this fun hehe

Turns out I failed to see [`.reader`](https://api.ktor.io/ktor-io/io.ktor.utils.io/reader.html) launches its own job, which resulted in multiple coroutines contending for the zip stream, each trying to write an entry... 🤦

The solution was just to get a channel and use that instead. Additionally, to mitigate the still blocking nature of Java's `ZipOutputStream`, I spawned the job in the appropriate [`Dispatchers.IO`](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html).  
Here it is:

```kotlin
ChannelProvider {
    val fileChannel = ByteChannel()
    val zos = ZipOutputStream(fileChannel.toOutputStream())
    coroScope.launch(Dispatchers.IO) {
        files.forEach { f ->
            val body = httpClient.get(f.url).bodyAsChannel()
            zos.putNextEntry(ZipEntry(f.filename))
            while (!body.isClosedForRead) {
                body.readRemaining(DEFAULT_BUFFER_SIZE.toLong()).let {
                    zos.writePacket(it)
                }
            }
            zos.closeEntry()
        }
        zos.close()
        fileChannel.close()
    }
    fileChannel
}
```