Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Todo App

Creating a simple Todo application using Akka actors in Scala involves several steps, including defining the messages that actors will use for communication, creating the actor behaviors, and setting up the actor system. This application will consist of a main actor, TodoManager, which manages todo items, and a simplified interface for adding and listing todos.

Step 1: Define the Messages

First, define the messages that will be used for interaction. In a Todo app, we typically need to add todos and list all existing todos.

sealed trait Command
final case class AddTodo(description: String) extends Command
final case object ListTodos extends Command
final case class Todos(items: List[String])

Step 2: Define the TodoManager Actor

The TodoManager actor will handle AddTodo and ListTodos messages. It maintains a list of todo items in its state.

import akka.actor.typed.Behavior
import akka.actor.typed.scaladsl.Behaviors

object TodoManager {
  def apply(): Behavior[Command] = manageTodos(Nil)

  private def manageTodos(todos: List[String]): Behavior[Command] =
    Behaviors.receive { (context, message) =>
      message match {
        case AddTodo(description) =>
          context.log.info(s"Adding todo: $description")
          manageTodos(todos :+ description)
        case ListTodos =>
          context.log.info(s"Current todos: $todos")
          Behaviors.same
      }
    }
}

Step 3: Set Up the Actor System and Interaction

Now, create the ActorSystem, and demonstrate adding some todos and listing them.

import akka.actor.typed.ActorSystem

object TodoApp extends App {
  val system: ActorSystem[Command] = ActorSystem(TodoManager(), "todoSystem")

  system ! AddTodo("Learn Akka Actors")
  system ! AddTodo("Build a TodoApp")
  system ! ListTodos

  // Shutdown the actor system after a delay to see the output
  import scala.concurrent.duration._
  import system.executionContext
  system.scheduler.scheduleOnce(2.seconds) {
    system.terminate()
  }
}

Running the Application

When you run this application, it will:

  • Create an ActorSystem with the TodoManager actor.
  • Send AddTodo messages to add new todos.
  • Send a ListTodos message to print out all current todos.
  • Finally, it schedules a system termination after a short delay so you can see the output before the application exits.