Thanks to visit codestin.com
Credit goes to medium.com

Sitemap

Handling input stream using kotlin

2 min readFeb 20, 2022
Press enter or click to view image in full size

In earlier days prior to kotlin

Press enter or click to view image in full size

Handling the input stream used to be a challenge. Whenever we think of reading data from a file stored in a project, That can involve reading an mp3 file, an mp4 file, just a text file, anything.

Press enter or click to view image in full size

We needed to write a lot of code on opening a stream and closing a stream. There would have been many chances of missing something and which would result in a memory leak and cause the bad performance of the application.

Solution

With the introduction of kotlin, it introduces a handy helper functions function that takes care of closing the stream

  • context.resources.openRawResource(resourceId).use { }
  • context.assets.open(fileName).use { }

Summary

We don’t need to worry about writing file handling actions like opening and closing streams that would have resulted in memory leakage. The usage of extension .use is very useful that takes care of this by default.

--

--

Responses (1)