How to read a file from the Internet using coroutines?

Asynchronous or non-blocking programming is the new reality. When creating server-side, desktop or mobile applications, it’s important to provide an experience that is not only fluid from the user’s perspective, but scalable when needed.

Kotlin solves this problem in a flexible way by providing coroutine support at the language level and delegating most of the functionality to libraries.

Let say we have a file at certain URL and to read that file we are taking the help of Coroutines.

All you need to do is launch it within a coroutine context, like this

private suspend fun urlRead() = withContext(Dispatchers.IO) {
val url = URL(MY_URL)
val stream = url.openStream()
stream.read()
}

where MY_URL is the URL where file is located.then you call it like this

lifecycleScope.launch {
val v = urlRead()
// TODO; use v
}

thats it.

you can also view this reference.

--

--

--

Data Analysis and ML| UI Designer | Python |Tableau |AR |Arduino |React Native

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

DevNews: How to Stake, Get Rewards and use the UND Web Wallet

The Multi-Cloud Environment in 2020: Advantages and Disadvantages

Multi-platform apps: are we there yet? | MEWS Systems

Unity’s Character Controller

[How To] Create your own Python Executable! (.exe file) Full In-Depth Tutorial

Top 10 Best Paying Jobs in Technology in 2022

Understanding CSS positioning properties from a beginner’s point of view.

Do You Even Process Bro?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akash Singh

Akash Singh

Data Analysis and ML| UI Designer | Python |Tableau |AR |Arduino |React Native

More from Medium

Java vs Kotlin, which is better for Android Application Development?

[Kotlin][Android Studio]unable to resolve class org.jetbrains.plugins.gradle.tooling.internal.ExtraM

androidx:appCompat:appcompat 升級至1.4.0編譯錯誤 AAPT: error: resource android:attr/lStar not found.

Context and Shared Preferences in Android — An Intro