DEV Community

Jorge
Jorge

Posted on

1

Serve huge file with RxJava2 in Micronaut

I'm working in a pet project where I'll serve large files (gif animated files arround 2mg each)
I'm using groovy and Micronaut because it is really very easy to create this kind of application

First version of the controller was very simple:

@Controller('/files')
FileController{
    @Get(value = "/{file}", produces = MediaType.IMAGE_GIF)
    byte[]image(@PathVariable String file) {        
       new File(file).bytes
     }
} 
Enter fullscreen mode Exit fullscreen mode

Main problem of this approach is you are blocking the request thread meanwhile you read the full file and send all the bytes with the consume of memory it implies

So we want to serve the resource in a "flowable" way using RxJava and sending chuncks of bytes without block the controller

@Controller("/test")
class FileController{
@Get(value = "/{file}", produces = MediaType.IMAGE_GIF)
Flowable<byte[]> image(@PathVariable String file) {
Flowable.create({ emitter ->
new File(file).withInputStream{ inputStream ->
int size=1024
byte[]buff = inputStream.readNBytes(size)
while( buff.length == size){
emitter.onNext(buff)
buff = inputStream.readNBytes(size)
}
emitter.onNext(buff)
emitter.onComplete()
}
}, BackpressureStrategy.BUFFER)
}
}
view raw FileController hosted with ❤ by GitHub

In this way what we return to Micronaut is a Promise who will be subscribe and consume in another thread. When the subscriber is consuming the Promise it will send chunck of bytes calling onNext many times and onComplete at the end

Using Flowable I've reduced the memory and the time required to show the gif because as soon the browser receives the first bytes it can start to show them

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay