2

My understanding is that Kotlin's coroutines are libraries, which leaves the only language-level feature of concurrency in Kotlin as the suspend keyword.

I'm still wrapping my head around coroutines in Kotlin, but I'm wondering if that may be overkill for my problem, which is updating a text view as soon as an HttpsURLConnection returns data. exception handling makes callbacks ugly enough that I want to avoid those if possible

does the suspend keyword simply mean that the runtime may suspend a function that takes a while to complete? or is suspension only enabled inside a coroutine? as a hypothetical, can I write

suspend fun getStringFromNetwork(): String {
  val request = URL("https:stackoverflow.com").openConnection()
  val result = readStream(request.inputStream)
  request.disconnect()
  return result
}

//and then elsewhere
foo()
val s = getStringFromNetwork()
bar(s)
baz()

and know that if getStringFromNetwork downloads 1 GB of data that baz() will be called in the meantime, while bar(s) waits for s to be populated by getStringFromNetwork?

PopKernel
  • 4,110
  • 5
  • 29
  • 51

1 Answers1

2

The "and then elsewhere" part calls getStringFromNetwork(), so it won't compile outside a suspend function (including suspend lambdas), and they can only be executed inside coroutines.

that baz() will be called in the meantime, while bar(s) waits for s to be populated by getStringFromNetwork?

No, if you write it this way, baz() will only start executing after bar(s) returns. But of course bar(s) can start a new coroutine which will do the actual work.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487