Nothing read from Azure Blob storage after downloading file in stream data

34 Views Asked by At

I'm fetching file from Azure blob storage with the following code but downloadedData is always empty string. I referred this MS document to read the file from the location. The file is not empty and does contain values. I tried with multiple type of files - text,pdf etc. But for all downloadedData is empty. How can I fix this issue?

      BlobAsyncClient blobAsyncClient = containerClient.getBlobAsyncClient("abc/file1.txt");
            ByteArrayOutputStream downloadData = new ByteArrayOutputStream();

            blobAsyncClient.downloadStream().subscribe(piece -> {
                try {
                    downloadData.write(piece.array());
                } catch (IOException ex) {
                    throw new UncheckedIOException(ex);
                }
            });
1

There are 1 best solutions below

0
Thiago Custodio On BEST ANSWER

The issue is because you're calling an Async method, but not awaiting for the completion.

You can call the .blockLast() method, or use the doOnComplete().

blobAsyncClient.downloadStream().subscribe(piece -> {
    try {
        downloadData.write(piece.array());
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}).blockLast();

or

blobAsyncClient.downloadStream().doOnNext(piece -> {
    try {
        downloadData.write(piece.array());
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}).doOnComplete(() -> {
    // This ensures that the downloadData is not accessed until it's fully populated
}).subscribe();