Handling input stream using kotlin
In earlier days prior to kotlin
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.
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.