0Pricing
Scala for Backend Engineering & Functional Programming · Ders

Eşzamansız İşlemleri Birleştirme

`Gelecek` değerlerini `map`, `flatMap` ve `for` ifadeleri gibi yöntemlerle birbirine bağlamayı ve birleştirmeyi öğrenin.

Eşzamansız İşlemleri Birleştirme, CoddyKit'te ücretsiz bir Scala for Backend Engineering & Functional Programming dersidir. Bu, 3 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Scala for Backend Engineering & Functional Programming öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Scala for Backend Engineering & Functional Programming kursu toplamda 3 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Why Chain Async Operations?

Futures help us run tasks without blocking the main program. But what if one task's result is needed for another, or we need to combine results from multiple tasks?

This is where composing Futures comes in handy. We'll learn how to chain and combine these asynchronous operations, making your Scala code more powerful and responsive.

`map`: Transform a Future's Result

The map method is used when you have a Future and you want to transform its successful result into another value. The transformation function you provide will be applied once the Future completes successfully.

  • It always returns a new Future.
  • It's perfect for simple, synchronous transformations on an asynchronous result.

`map` in Action (Code)

Here, we get a number from a Future and then double it using map. The transformation happens only after the initial Future finishes.

import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

object Main {
  def main(args: Array[String]): Unit = {
    val originalFuture: Future[Int] = Future {
      Thread.sleep(100) // Simulate work
      10
    }

    val doubledFuture: Future[Int] = originalFuture.map(value => value * 2)

    val result = Await.result(doubledFuture, 1.second)
    println(s"Doubled value: $result")
  }
}

`flatMap`: Chaining Futures

Sometimes, the successful result of one Future needs to kick off another Future. This is where flatMap shines. It "flattens" a Future of a Future (Future[Future[T]]) into a single Future[T].

  • Use it when your transformation function returns a Future.
  • It's essential for sequential asynchronous operations.

`flatMap` in Action (Code)

We fetch a user ID, then use that ID to fetch user details. Each step is an asynchronous operation returning a Future. flatMap ensures they run in sequence.

import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

object Main {
  def main(args: Array[String]): Unit = {
    def fetchUserId(): Future[Int] = Future {
      Thread.sleep(50)
      123
    }

    def fetchUserDetails(userId: Int): Future[String] = Future {
      Thread.sleep(100)
      s"User $userId details"
    }

    val userDetailsFuture: Future[String] = fetchUserId().flatMap { userId =>
      fetchUserDetails(userId)
    }

    val result = Await.result(userDetailsFuture, 1.second)
    println(s"Details: $result")
  }
}

`map` vs. `flatMap`: Key Difference

It's common to confuse map and flatMap. Remember:

  • map: Your function returns a regular value (e.g., Int, String). Future[A].map(A => B) results in Future[B].
  • flatMap: Your function returns another Future (e.g., Future[Int], Future[String]). Future[A].flatMap(A => Future[B]) results in Future[B].

flatMap is for chaining async operations, while map is for transforming an async result synchronously.

`for` Comprehensions: Elegant Chaining

Scala's for comprehensions provide a clean, readable syntax for chaining operations that involve map and flatMap. They are purely syntactic sugar, meaning the compiler translates them into a series of map, flatMap, and filter calls.

When you have multiple dependent Future operations, for comprehensions make the code look almost synchronous.

`for` Comprehension Code

This example uses a for comprehension to chain the same user ID and details fetching logic we saw with flatMap. Notice how much cleaner it looks!

import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

object Main {
  def main(args: Array[String]): Unit = {
    def fetchUserId(): Future[Int] = Future {
      Thread.sleep(50)
      123
    }

    def fetchUserName(userId: Int): Future[String] = Future {
      Thread.sleep(100)
      s"Alice (ID: $userId)"
    }

    val userFuture: Future[String] = for {
      id <- fetchUserId()
      name <- fetchUserName(id)
    } yield name

    val result = Await.result(userFuture, 1.second)
    println(s"User name: $result")
  }
}

`zip`: Combining Independent Results

What if you have two independent Futures and want to combine their results once both are complete? The zip method is perfect for this. It takes another Future and returns a new Future that holds a pair (a Tuple) of their successful results.

Both futures run concurrently, and zip waits for both to finish.

import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

object Main {
  def main(args: Array[String]): Unit = {
    val futureA = Future {
      Thread.sleep(100)
      "Hello"
    }

    val futureB = Future {
      Thread.sleep(50)
      "World"
    }

    val combinedFuture: Future[(String, String)] = futureA.zip(futureB)

    val (greeting, subject) = Await.result(combinedFuture, 1.second)
    println(s"$greeting $subject!")
  }
}

Quick Check: Composing Futures

Consider the following Scala code snippet. What will be the final value printed?

import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

object Main {
  def main(args: Array[String]): Unit = {
    val f1 = Future { 5 }
    val f2 = f1.map(x => x + 2)
    val f3 = f2.flatMap(y => Future { y * 3 })

    val result = Await.result(f3, 1.second)
    println(result)
  }
}

Recap: Chaining Async Tasks

You've learned powerful ways to compose Scala Futures:

  • map: Transforms a Future's successful result into a new value.
  • flatMap: Chains two Futures where the result of the first is used to start the second.
  • for comprehensions: Provide a clean, synchronous-looking syntax for flatMap and map chains.
  • zip: Combines the results of two independent Futures into a tuple.

These tools are crucial for building responsive and efficient asynchronous applications in Scala!

Sıkça Sorulan Sorular

“Eşzamansız İşlemleri Birleştirme” dersi ücretsiz mi?

Evet — “Eşzamansız İşlemleri Birleştirme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Scala for Backend Engineering & Functional Programming kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Scala for Backend Engineering & Functional Programming kursu toplamda 3 dersten oluşur.

“Eşzamansız İşlemleri Birleştirme” dersinde ne öğreneceğim?

`Gelecek` değerlerini `map`, `flatMap` ve `for` ifadeleri gibi yöntemlerle birbirine bağlamayı ve birleştirmeyi öğrenin. Scala for Backend Engineering & Functional Programming ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Scala for Backend Engineering & Functional Programming öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Scala for Backend Engineering & Functional Programming, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 3 dersinin 2. dersidir.

“Eşzamansız İşlemleri Birleştirme” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Scala for Backend Engineering & Functional Programming dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Scala for Backend Engineering & Functional Programming dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Future ve Promise'e Giriş
  2. Eşzamansız İşlemleri Birleştirme
  3. Future İçinde Hata İşleme
← Scala for Backend Engineering & Functional Programming Sayfasına Dön