alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Akka/Scala example source code file (ViewExample.scala)

This example Akka source code file (ViewExample.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Akka and Scala source code examples by using tags.

All credit for the original source code belongs to akka.io; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Akka tags/keywords

actor, actorsystem, akka, app, concurrent, duration, examplepersistentactor, exampleview, int, persistence, persistentactor, persistentview, snapshotoffer, string, time, viewexample

The ViewExample.scala Akka example source code

package sample.persistence

import scala.concurrent.duration._

import akka.actor._
import akka.persistence._

object ViewExample extends App {
  class ExamplePersistentActor extends PersistentActor {
    override def persistenceId = "sample-id-4"

    var count = 1

    def receiveCommand: Actor.Receive = {
      case payload: String =>
        println(s"persistentActor received ${payload} (nr = ${count})")
        persist(payload + count) { evt =>
          count += 1
        }
    }

    def receiveRecover: Actor.Receive = {
      case _: String => count += 1
    }
  }

  class ExampleView extends PersistentView {
    private var numReplicated = 0

    override def persistenceId: String = "sample-id-4"
    override def viewId = "sample-view-id-4"

    def receive = {
      case "snap" =>
        saveSnapshot(numReplicated)
      case SnapshotOffer(metadata, snapshot: Int) =>
        numReplicated = snapshot
        println(s"view received snapshot offer ${snapshot} (metadata = ${metadata})")
      case payload if isPersistent =>
        numReplicated += 1
        println(s"view received persistent ${payload} (num replicated = ${numReplicated})")
      case payload =>
        println(s"view received not persitent ${payload}")
    }

  }

  val system = ActorSystem("example")

  val persistentActor = system.actorOf(Props(classOf[ExamplePersistentActor]))
  val view = system.actorOf(Props(classOf[ExampleView]))

  import system.dispatcher

  system.scheduler.schedule(Duration.Zero, 2.seconds, persistentActor, "scheduled")
  system.scheduler.schedule(Duration.Zero, 5.seconds, view, "snap")
}

Other Akka source code examples

Here is a short list of links related to this Akka ViewExample.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.