en

Mark Murphy

  • b4777467766has quoted2 years ago
    In Android, JavaFx, and other GUI environments, updates to the UI are single-threaded, with a specific thread being responsible for those updates. Typically, we have to do any substantial work on background threads, so we do not tie up the UI thread and prevent it from updating the UI.
  • b4777467766has quoted2 years ago
    Callbacks are simply objects representing chunks of code to be invoked when a certain condition occurs. In the case of asynchronous operations, the “certain condition” often is “when the operation completes, successfully or with an error”.
  • b4777467766has quoted2 years ago
    “Callback hell” occurs when you have lots of nested callbacks, such as this Java snippet:
  • b4777467766has quoted2 years ago
    The ugliness comes from the challenges in following the execution flow through layers upon layers of callbacks. Ideally, the syntax for our code would not be inextricably tied to the threading model of our code.
  • b4777467766has quoted2 years ago
    If doSomething(), doTheNextThing(), and doSomethingElse() all employ coroutines, our code invoking those functions could look something like this:

    someCoroutineScope.launch {
    doSomething()
    try {
    val result = doSomethingElse(doTheNextThing())
    // TODO
    } catch (t: Throwable) {
    // TODO
    }
    }
    There is a lot of “plumbing” in Kotlin — both in the language and in libraries — that makes this simple syntax possible. We, as users of Kotlin, get to enjoy the simple syntax.
  • b4777467766has quoted2 years ago
    While one element of coroutines (the suspend keyword) is part of the language, the rest comes from libraries. You will need to add these libraries to your project in order to be able to use coroutines. Exactly how you add these libraries will depend a lot on your project type and the build system that you are using.
  • b4777467766has quoted2 years ago
    Note that these versions are somewhat independent of the overall Kotlin version (1.4).
  • b4777467766has quoted2 years ago
    For an Android project, you would want to add a dependency on org.jetbrains.kotlinx:kotlinx-coroutines-android. This has transitive dependencies to pull in the core coroutines code, plus it has Android-specific elements.
  • b4777467766has quoted2 years ago
    Primarily, a CoroutineScope is responsible for canceling and cleaning up coroutines when the CoroutineScope is no longer needed. GlobalScope will be set up to support the longest practical lifetime: the lifetime of the process that is running the Kotlin code.
  • b4777467766has quoted2 years ago
    Part of the configuration that you can provide to a coroutine builder is a dispatcher. This indicates what thread pool (or similar structure) should be used for executing the code inside of the coroutine.
fb2epub
Drag & drop your files (not more than 5 at once)