14 Temmuz 2021 Çarşamba

Kotlin suspend Anahtar Kelimesi

Suspension Function
Açıklaması şöyle.
Suspending functions may suspend the execution of the current coroutine without blocking the current thread.
suspend vs Callback
Açıklaması  şöyle
Suspend functions are a direct replacement for callbacks — it is one of the basic premises behind structured concurrency. Callbacks make code hard to follow (ie. they make your code unstructured). The classic example of this is the pyramid of doom or callback hell. Coroutines (represented primarily as suspend functions in Kotlin) are designed to clean that kind of code up — callbacks are no longer required
suspend vs Flow
Açıklaması şöyle
When designing your methods and functions, start with a suspend function and if you get stuck, change it to a Flow.
 
Kotlin ve suspend Anahtar Kelimesi
Açıklaması şöyle.
You may find functions like kotlinx’s delay or Ktor’s HttpClient.post that need to wait for something or do intensive work before returning, and are marked with the suspend keyword.
Örnek
Şöyle yaparız
suspend fun delay(timeMillis: Long) {...}
suspend fun someNetworkCallReturningValue(): SomeType {
 ...
}
Suspend return Type
Açıklaması şöyle
The suspending world is nicely sequential
You have probably noticed that suspending functions don’t have special return types. They are really declared just like usual functions. We don’t need any wrapper like Java’s Future or JavaScript's Promise. This confirms that suspending functions are not asynchronous themselves (at least from the point of view of the caller), unlike JavaScript’s async functions, which return promises.

This is what makes asynchronous stuff easy to reason about in Kotlin. Inside a suspending function, calls to other suspending functions behave like normal function calls: we need to wait for the execution of the called function before getting the return value and executing the rest of the code.
Ancak google tarafından önerilen şey bir Result sınıfı tanımlamak. Böylece when ile kullanılabilir. Şöyle yaparız
sealed class Result<out R> {
  data class Success<out T>(val data: T) : Result<T>()
  data class Error(val exception: Exception) : Result<Nothing>()
}
when (result) {
  is Result.Success<LoginResponse> -> // Happy path
  else -> // Show error in UI
}

Coroutine builders
1. runBlocking metodu
Örnek
Şöyle yaparız
fun main() { 
  println("Hello,")
    
  // we create a coroutine running the provided suspending lambda
  // and block the main thread while waiting for the coroutine to finish its
//execution
  runBlocking {
    // now we are inside a coroutine
    delay(2000L) // suspends the current coroutine for 2 seconds
  }
    
  // will be executed after 2 seconds
  println("World!")
}
2. funCatching
Kendi Result sınıfını döner. Bizim artık Result sınıfı tanımlamamıza gerek kalmaz. Şöyle yaparız
val statusResult: Result<String> = runCatching {
  // function that may throw exception that needs to be handled
  repository.userStatusNetworkRequest(username)
}.onSuccess { status: String ->
  println("User status is: $status")
}.onFailure { error: Throwable ->
  println("Go network error: ${error.message}")
}
3. launch metodu - Fire and Forget
Örnek
Şöyle yaparız
fun main() { 
    GlobalScope.launch { // launch new coroutine in background and continue
        delay(1000L)
        println("World!")
    }
    println("Hello,") // main thread continues here immediately
    runBlocking {     // but this expression blocks the main thread
        delay(2000L)  // ... while we delay for 2 seconds to keep JVM alive
    } 
}
4. await metodu - Get Result
Örnek
Şöyle yaparız
fun main() {
    val deferredResult: Deferred<String> = GlobalScope.async {
        delay(1000L)
        "World!"
    }
    
    runBlocking {
        println("Hello, ${deferredResult.await()}")
    }
}





Hiç yorum yok:

Yorum Gönder