SlideShare a Scribd company logo
1 of 38
Concurrent Application
Development using Scala
Sergei Semenchuk
https://github.com/binjip978/ConcTalk
FP 101
def withdrawMoney(user: String,
password: String, amount: Int): Money = {
// some logic
Money(amount)
}
def buyBook(name: String, cash: Money): Book = {
// some logic
Book("Functional Programming in Scala")
}
val cash = withdrawMoney("user1", "password2", 100)
val book = buyBook("Functional Programming in Scala", cash)
println(book)
trait Try[+T]
case class Success[+T](value: T) extends Try[T]
case class Failure(e: Throwable) extends Try[Nothing]
val success = Success(100)
success match {
case Success(v) => println(v)
case Failure(e) => println(s"Error: $e")
}
val v = Try {
if (scala.util.Random.nextBoolean() == true) 12
else 1 / 0
}
v match {
case Success(v) => println(v)
case Failure(e) => println("Error!")
}
def withdrawMoney(user: String,
password: String, amount: Int): Try[Money] = {
Try(Money(amount))
}
def buyBook(name: String, cash: Money): Try[Book] = {
Try(Book("Functional Programming in Scala"))
}
withdrawMoney("user1", "password2", 100) match {
case Success(cash) => {
buyBook("Functional Programming in Scala", cash) match {
case Success(book) => println(book)
case Failure(e) => println(s"Error occurred: $e")
}
}
case Failure(e) => println(s"Error occurred: $e")
}
case class Money(amount: Int)
case class Book(title: String)
def withdrawMoney(user: String, password:
String, amount: Int): Try[Money] = {
// some logic
Try(Money(amount))
}
def buyBook(name: String, cash: Money): Try[Book] = {
// some logic
Try(Book("Functional Programming in Scala"))
}
for {
cash <- withdrawMoney("user1", "password2", 100)
book <- buyBook("Functional Programming in Scala", cash)
} println(book)
case class Money(amount: Int)
case class Book(title: String)
def withdrawMoney(user: String, password:
String, amount: Int): Try[Money] = {
// some logic
Try(Money(amount))
}
def buyBook(name: String, cash: Money): Try[Book] = {
// some logic
Try(Book("Functional Programming in Scala"))
}
val book = withdrawMoney("user1", "password2", 100)
.flatMap(cash => buyBook("Functional Programming in Scala", cash))
book.foreach(b => println(b))
}
trait Option[+A]
case class Some[+A](v: A) extends Option[A]
case object None extends Option[Nothing]
def unit[A](v: A): Option[A] = {
Some(v)
}
def flatMap[A, B](op: Option[A])(f: A => Option[B]): Option[B]
= op match {
case Some(v) => f(v)
case None => None
}
def map[A, B](op: Option[A])(f: A => B): Option[B] = {
flatMap(op)(x => unit(f(x)))
}
The Four Essential Effects In Programming
One Many
Synchronous T/Try[T] Iterable[T]
Asynchronous Future[T] Observable[T]
Asynchronous Programming with
Futures
and Promises
//def apply[T](b: =>T)(implicit e: ExecutionContext): Future[T]
val f = Future { println("Hello World!") }
println(f.isCompleted)
Thread.sleep(1000)
println(f.isCompleted)
def getUrlSpec(): Future[List[String]] = Future {
val url = "http://www.w3.org/Addressing/URL/url-spec.txt"
val f = scala.io.Source.fromURL(url)
try {
f.getLines().toList
} finally {
f.close()
}
}
def find(lines: List[String], keyword: String):String = {
lines.zipWithIndex.collect {
case (line, n) if (line.contains(keyword)) => (n, line)
} mkString("n")
}
val f = getUrlSpec()
f.foreach { case (lines) => println(find(lines, “telnet")) }
Thread.sleep(5000)
val f: Future[Int] = Future { 1 / 0 }
f onComplete {
case Success(v) => println("Surprise!")
case Failure(e) => println(s"Error: $e")
}
Thread.sleep(1000)
val f1: Future[Int] = Future { 1345 }
val f2: Future[Int] = Future { 2356 }
val f3: Future[Int] = Future { 4563 }
val comp1: Future[Int] = f1.flatMap(v1 => f2.flatMap(v2 =>
f3.map(v3 => v1 + v2 + v3)))
val comp2: Future[Int] = for {
v1 <- f1
v2 <- f2
v3 <- f3
} yield v1 + v2 + v3
//comp1 === comp2
comp1.onSuccess { case(x: Int) => println(x) }
comp2.onSuccess { case(x: Int) => println(x) }
Thread.sleep(1000)
}
val f1 = Future { 1 }
val f2 = Future { 1 / 0 }
val f3 = Future { 2 }
val c = for {
v1 <- f1
v2 <- f2
v3 <- f3
} yield v1 + v2 + v3
c onComplete {
case Success(v) => println(v)
case Failure(e) => println(s"error $e")
}
Thread.sleep(1000)
def getRandonName = Future { "John" }
def getIdByName(name: String) = Future { 12 }
def getDepotIdById(id: Int) = Future { 34 }
def getDepotName(id: Int) = Future { "A depot" }
val f = for {
name <- getRandonName
userId <- getIdByName(name)
depotId <- getDepotIdById(userId)
depotName <- getDepotName(userId)
} yield s"$name from $depotName"
f.onSuccess {
case (v) => println(v)
}
Thread.sleep(1000)
def getUSDQuote = Future { 1.2 }
def getEURQuote = Future { 0.8 }
val p = for {
usd <- getUSDQuote
eur <- getEURQuote
if (eur > usd)
} yield usd
p onFailure { case (e) => println("Error: " + e) }
Thread.sleep(1000)
val f1: Future[Int] = Future { 1 / 0 }
val f2: Future[Any] = f1.recover {
case (exp) => s"error happend: $exp"
}
f2.onComplete {
case Success(v) => println(s"if success: $v")
case Failure(e) => println(s"if failure: $e")
}
Thread.sleep(1000)
val p = Promise[String]
val q = Promise[String]
p.future foreach { case x => println(x)}
q.future.failed foreach { case e => println(s"error: " + e)}
p.complete(Success("Promise complete"))
q.complete(Failure(new Exception))
val z = Promise[Int]
z.future onComplete {
case Success(v) => println(v)
case Failure(e) => println(s"Error: $e")
}
z.complete(Try(1 / 0))
def first[T](xs: List[Future[T]]): Future[T] = {
val p = Promise[T]
for {
x <- xs
} p.tryCompleteWith(x)
p.future
}
val f = first(List(Future{ Thread.sleep(2000);
12 }, Future { new Exception }))
f.foreach { case x => println(x) }
val urlSpecSize = Future {
val url = "http://www.scala-lang.org"
scala.io.Source.fromURL(url).size
}
// how much we should wait until exception
val size = Await.result(urlSpecSize, 10 seconds)
println(size)
Concurrent Programming with
Reactive Extensions
val observable: Observable[String] = Observable.items("A", "B", "C")
observable.subscribe(str => println(str.toLowerCase))
observable.subscribe(str => println(str * 7))
val o: Observable[Long] = Observable.timer(2 second)
o.subscribe(x => println(x))
o.subscribe(x => println(x + 1000))
val ex = new RuntimeException
val observable: Observable[Int] = Observable.items(0, 1, 2) ++
Observable.error(ex) ++
Observable.items(3, 4)
observable.subscribe(
value => println(value),
error => println(s"an error occurred: $error")
)
val countries = List("Germany", "US", "Japan")
val observable = Observable.from(countries)
observable.subscribe(new Observer[String] {
override def onNext(c: String) = println(s"Nice to live in $c”)
override def onError(e: Throwable) = println(“error!!!")
override def onCompleted() = println("That all list!")
})
// def create(f: Observer[T] => Subscription): Observable[T]
val vms = Observable.apply[String] { obs =>
obs.onNext("JVM")
obs.onNext("LLVM")
obs.onNext("Dalvik")
obs.onCompleted()
Subscription
}
vms.subscribe(str => println(str))
}
val f = Future("Future")
val observable = Observable.apply[String] { obs =>
f onComplete {
case Success(v) => {
obs.onNext(v)
obs.onCompleted()
}
case Failure(e) => {
obs.onError(e)
}
}
Subscription
}
observable.subscribe(str => println(str))
def coldObserver(directory: String): Observable[String] = {
Observable.apply[String] { obs =>
val fileMonitor = new FileAlterationMonitor(1000)
val fileObs = new FileAlterationObserver(directory)
val fileListener = new FileAlterationListenerAdaptor {
override def onFileChange(file: java.io.File): Unit = {
obs.onNext(file.getName)
}
}
fileObs.addListener(fileListener)
fileMonitor.addObserver(fileObs)
fileMonitor.start()
Subscription {
fileMonitor.stop()
}
}
}
def hotObserver(directory: String): Observable[String] = {
val fileMonitor = new FileAlterationMonitor(1000)
val fileObs = new FileAlterationObserver(directory)
fileMonitor.addObserver(fileObs)
Observable.apply[String] { obs =>
val fileListener = new FileAlterationListenerAdaptor {
override def onFileChange(file: java.io.File): Unit = {
obs.onNext(file.getName)
}
}
fileObs.addListener(fileListener)
Subscription { fileObs.removeListener(
fileListener) }
}
}
val odds = Observable.interval(0.5 seconds)
.filter(x => x % 2 == 1)
.map(x => s"num $x")
.take(5)
odds.subscribe(str => println(str))
def fetchQuote(): Future[String] = Future {
blocking {
val url = “http://www.iheartquotes.com/api/v1/random?" + "show_permalink=false&show_source=false"
Source.fromURL(url).getLines().mkString
}
}
def fetchQuoteObservable(): Observable[String] = {
Observable.from(fetchQuote())
}
def quotes(): Observable[Observable[String]] = {
Observable.interval(1 second).take(5).map {
n => fetchQuoteObservable().map(txt => s"$n) $txt")
}
}
val concat: Observable[String] = quotes().concat
concat.subscribe(q => println(q)) /
val flatten: Observable[String] = quotes().flatten //
val qs: Observable[String] = for {
n <- Observable.interval(1 second).take(5)
txt <- fetchQuoteObservable()
} yield s"$n) $txt"
qs.subscribe(q => println(q))
def randomQuote() = Observable.apply[String] {
obs =>
val url = "http://www.iheartquotes.com/api/v1/random?" +
"show_permalink=false&show_source=false"
obs.onNext(Source.fromURL(url).getLines.mkString)
obs.onCompleted()
Subscription
}
import Observable._
def errorMessage = items("Retrying...") ++ error(new Exception)
def quoteMessage(): Observable[String] = for {
text <- randomQuote()
message <- if (text.size < 50) items(text)
else errorMessage
} yield message
quoteMessage().retry(5).subscribe(str => println(str))
val status = Observable.items("1", "2") ++ Observable.error(new Exception)
val fixedStatus = status.onErrorReturn(e => "exception")
fixedStatus.subscribe(str => println(str))
val continuedStatus = status.onErrorResumeNext(e =>
Observable.items("4", "5"))
continuedStatus.subscribe(str => println(str))
Concurrent Application Development using Scala
Concurrent Application Development using Scala
Concurrent Application Development using Scala

More Related Content

What's hot

[SI] Ada Lovelace Day 2014 - Tampon Run
[SI] Ada Lovelace Day 2014  - Tampon Run[SI] Ada Lovelace Day 2014  - Tampon Run
[SI] Ada Lovelace Day 2014 - Tampon RunMaja Kraljič
 
20191116 custom operators in swift
20191116 custom operators in swift20191116 custom operators in swift
20191116 custom operators in swiftChiwon Song
 
SAT/SMT solving in Haskell
SAT/SMT solving in HaskellSAT/SMT solving in Haskell
SAT/SMT solving in HaskellMasahiro Sakai
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Futureemptysquare
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new featuresGephenSG
 
Functional and reactive u is gwt.create 2015
Functional and reactive u is gwt.create 2015Functional and reactive u is gwt.create 2015
Functional and reactive u is gwt.create 2015hezamu
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsFranco Lombardo
 
ClojurianからみたElixir
ClojurianからみたElixirClojurianからみたElixir
ClojurianからみたElixirKent Ohashi
 
The Ring programming language version 1.8 book - Part 73 of 202
The Ring programming language version 1.8 book - Part 73 of 202The Ring programming language version 1.8 book - Part 73 of 202
The Ring programming language version 1.8 book - Part 73 of 202Mahmoud Samir Fayed
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveEleanor McHugh
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
 
openFrameworks 007 - utils
openFrameworks 007 - utilsopenFrameworks 007 - utils
openFrameworks 007 - utilsroxlu
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기Suyeol Jeon
 
20180310 functional programming
20180310 functional programming20180310 functional programming
20180310 functional programmingChiwon Song
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲームNoritada Shimizu
 

What's hot (20)

Error Handling in Scala
Error Handling in ScalaError Handling in Scala
Error Handling in Scala
 
C Language Lecture 17
C Language Lecture 17C Language Lecture 17
C Language Lecture 17
 
[SI] Ada Lovelace Day 2014 - Tampon Run
[SI] Ada Lovelace Day 2014  - Tampon Run[SI] Ada Lovelace Day 2014  - Tampon Run
[SI] Ada Lovelace Day 2014 - Tampon Run
 
20191116 custom operators in swift
20191116 custom operators in swift20191116 custom operators in swift
20191116 custom operators in swift
 
SAT/SMT solving in Haskell
SAT/SMT solving in HaskellSAT/SMT solving in Haskell
SAT/SMT solving in Haskell
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new features
 
Functional and reactive u is gwt.create 2015
Functional and reactive u is gwt.create 2015Functional and reactive u is gwt.create 2015
Functional and reactive u is gwt.create 2015
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functions
 
ClojurianからみたElixir
ClojurianからみたElixirClojurianからみたElixir
ClojurianからみたElixir
 
PROGRAM pod
PROGRAM podPROGRAM pod
PROGRAM pod
 
The Ring programming language version 1.8 book - Part 73 of 202
The Ring programming language version 1.8 book - Part 73 of 202The Ring programming language version 1.8 book - Part 73 of 202
The Ring programming language version 1.8 book - Part 73 of 202
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
openFrameworks 007 - utils
openFrameworks 007 - utilsopenFrameworks 007 - utils
openFrameworks 007 - utils
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 
20180310 functional programming
20180310 functional programming20180310 functional programming
20180310 functional programming
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 

Similar to Concurrent Application Development using Scala

Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de donnéesRomain Lecomte
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2Hang Zhao
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 
Kotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresKotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresiMasters
 
Dip into Coroutines - KTUG Munich 202303
Dip into Coroutines - KTUG Munich 202303Dip into Coroutines - KTUG Munich 202303
Dip into Coroutines - KTUG Munich 202303Alex Semin
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix TaskHermann Hueck
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Monads - Dublin Scala meetup
Monads - Dublin Scala meetupMonads - Dublin Scala meetup
Monads - Dublin Scala meetupMikhail Girkin
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksSeniorDevOnly
 

Similar to Concurrent Application Development using Scala (20)

Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
 
Monadologie
MonadologieMonadologie
Monadologie
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
Kotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresKotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan Soares
 
Dip into Coroutines - KTUG Munich 202303
Dip into Coroutines - KTUG Munich 202303Dip into Coroutines - KTUG Munich 202303
Dip into Coroutines - KTUG Munich 202303
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Monads - Dublin Scala meetup
Monads - Dublin Scala meetupMonads - Dublin Scala meetup
Monads - Dublin Scala meetup
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Go a crash course
Go   a crash courseGo   a crash course
Go a crash course
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 

Recently uploaded (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

Concurrent Application Development using Scala

  • 1. Concurrent Application Development using Scala Sergei Semenchuk https://github.com/binjip978/ConcTalk
  • 3. def withdrawMoney(user: String, password: String, amount: Int): Money = { // some logic Money(amount) } def buyBook(name: String, cash: Money): Book = { // some logic Book("Functional Programming in Scala") } val cash = withdrawMoney("user1", "password2", 100) val book = buyBook("Functional Programming in Scala", cash) println(book)
  • 4. trait Try[+T] case class Success[+T](value: T) extends Try[T] case class Failure(e: Throwable) extends Try[Nothing] val success = Success(100) success match { case Success(v) => println(v) case Failure(e) => println(s"Error: $e") }
  • 5. val v = Try { if (scala.util.Random.nextBoolean() == true) 12 else 1 / 0 } v match { case Success(v) => println(v) case Failure(e) => println("Error!") }
  • 6. def withdrawMoney(user: String, password: String, amount: Int): Try[Money] = { Try(Money(amount)) } def buyBook(name: String, cash: Money): Try[Book] = { Try(Book("Functional Programming in Scala")) } withdrawMoney("user1", "password2", 100) match { case Success(cash) => { buyBook("Functional Programming in Scala", cash) match { case Success(book) => println(book) case Failure(e) => println(s"Error occurred: $e") } } case Failure(e) => println(s"Error occurred: $e") }
  • 7. case class Money(amount: Int) case class Book(title: String) def withdrawMoney(user: String, password: String, amount: Int): Try[Money] = { // some logic Try(Money(amount)) } def buyBook(name: String, cash: Money): Try[Book] = { // some logic Try(Book("Functional Programming in Scala")) } for { cash <- withdrawMoney("user1", "password2", 100) book <- buyBook("Functional Programming in Scala", cash) } println(book)
  • 8. case class Money(amount: Int) case class Book(title: String) def withdrawMoney(user: String, password: String, amount: Int): Try[Money] = { // some logic Try(Money(amount)) } def buyBook(name: String, cash: Money): Try[Book] = { // some logic Try(Book("Functional Programming in Scala")) } val book = withdrawMoney("user1", "password2", 100) .flatMap(cash => buyBook("Functional Programming in Scala", cash)) book.foreach(b => println(b)) }
  • 9. trait Option[+A] case class Some[+A](v: A) extends Option[A] case object None extends Option[Nothing] def unit[A](v: A): Option[A] = { Some(v) } def flatMap[A, B](op: Option[A])(f: A => Option[B]): Option[B] = op match { case Some(v) => f(v) case None => None } def map[A, B](op: Option[A])(f: A => B): Option[B] = { flatMap(op)(x => unit(f(x))) }
  • 10. The Four Essential Effects In Programming One Many Synchronous T/Try[T] Iterable[T] Asynchronous Future[T] Observable[T]
  • 12. //def apply[T](b: =>T)(implicit e: ExecutionContext): Future[T] val f = Future { println("Hello World!") } println(f.isCompleted) Thread.sleep(1000) println(f.isCompleted)
  • 13. def getUrlSpec(): Future[List[String]] = Future { val url = "http://www.w3.org/Addressing/URL/url-spec.txt" val f = scala.io.Source.fromURL(url) try { f.getLines().toList } finally { f.close() } } def find(lines: List[String], keyword: String):String = { lines.zipWithIndex.collect { case (line, n) if (line.contains(keyword)) => (n, line) } mkString("n") } val f = getUrlSpec() f.foreach { case (lines) => println(find(lines, “telnet")) } Thread.sleep(5000)
  • 14. val f: Future[Int] = Future { 1 / 0 } f onComplete { case Success(v) => println("Surprise!") case Failure(e) => println(s"Error: $e") } Thread.sleep(1000)
  • 15. val f1: Future[Int] = Future { 1345 } val f2: Future[Int] = Future { 2356 } val f3: Future[Int] = Future { 4563 } val comp1: Future[Int] = f1.flatMap(v1 => f2.flatMap(v2 => f3.map(v3 => v1 + v2 + v3))) val comp2: Future[Int] = for { v1 <- f1 v2 <- f2 v3 <- f3 } yield v1 + v2 + v3 //comp1 === comp2 comp1.onSuccess { case(x: Int) => println(x) } comp2.onSuccess { case(x: Int) => println(x) } Thread.sleep(1000) }
  • 16. val f1 = Future { 1 } val f2 = Future { 1 / 0 } val f3 = Future { 2 } val c = for { v1 <- f1 v2 <- f2 v3 <- f3 } yield v1 + v2 + v3 c onComplete { case Success(v) => println(v) case Failure(e) => println(s"error $e") } Thread.sleep(1000)
  • 17. def getRandonName = Future { "John" } def getIdByName(name: String) = Future { 12 } def getDepotIdById(id: Int) = Future { 34 } def getDepotName(id: Int) = Future { "A depot" } val f = for { name <- getRandonName userId <- getIdByName(name) depotId <- getDepotIdById(userId) depotName <- getDepotName(userId) } yield s"$name from $depotName" f.onSuccess { case (v) => println(v) } Thread.sleep(1000)
  • 18. def getUSDQuote = Future { 1.2 } def getEURQuote = Future { 0.8 } val p = for { usd <- getUSDQuote eur <- getEURQuote if (eur > usd) } yield usd p onFailure { case (e) => println("Error: " + e) } Thread.sleep(1000)
  • 19. val f1: Future[Int] = Future { 1 / 0 } val f2: Future[Any] = f1.recover { case (exp) => s"error happend: $exp" } f2.onComplete { case Success(v) => println(s"if success: $v") case Failure(e) => println(s"if failure: $e") } Thread.sleep(1000)
  • 20. val p = Promise[String] val q = Promise[String] p.future foreach { case x => println(x)} q.future.failed foreach { case e => println(s"error: " + e)} p.complete(Success("Promise complete")) q.complete(Failure(new Exception)) val z = Promise[Int] z.future onComplete { case Success(v) => println(v) case Failure(e) => println(s"Error: $e") } z.complete(Try(1 / 0))
  • 21. def first[T](xs: List[Future[T]]): Future[T] = { val p = Promise[T] for { x <- xs } p.tryCompleteWith(x) p.future } val f = first(List(Future{ Thread.sleep(2000); 12 }, Future { new Exception })) f.foreach { case x => println(x) }
  • 22. val urlSpecSize = Future { val url = "http://www.scala-lang.org" scala.io.Source.fromURL(url).size } // how much we should wait until exception val size = Await.result(urlSpecSize, 10 seconds) println(size)
  • 24. val observable: Observable[String] = Observable.items("A", "B", "C") observable.subscribe(str => println(str.toLowerCase)) observable.subscribe(str => println(str * 7))
  • 25. val o: Observable[Long] = Observable.timer(2 second) o.subscribe(x => println(x)) o.subscribe(x => println(x + 1000))
  • 26. val ex = new RuntimeException val observable: Observable[Int] = Observable.items(0, 1, 2) ++ Observable.error(ex) ++ Observable.items(3, 4) observable.subscribe( value => println(value), error => println(s"an error occurred: $error") )
  • 27. val countries = List("Germany", "US", "Japan") val observable = Observable.from(countries) observable.subscribe(new Observer[String] { override def onNext(c: String) = println(s"Nice to live in $c”) override def onError(e: Throwable) = println(“error!!!") override def onCompleted() = println("That all list!") })
  • 28. // def create(f: Observer[T] => Subscription): Observable[T] val vms = Observable.apply[String] { obs => obs.onNext("JVM") obs.onNext("LLVM") obs.onNext("Dalvik") obs.onCompleted() Subscription } vms.subscribe(str => println(str)) }
  • 29. val f = Future("Future") val observable = Observable.apply[String] { obs => f onComplete { case Success(v) => { obs.onNext(v) obs.onCompleted() } case Failure(e) => { obs.onError(e) } } Subscription } observable.subscribe(str => println(str))
  • 30. def coldObserver(directory: String): Observable[String] = { Observable.apply[String] { obs => val fileMonitor = new FileAlterationMonitor(1000) val fileObs = new FileAlterationObserver(directory) val fileListener = new FileAlterationListenerAdaptor { override def onFileChange(file: java.io.File): Unit = { obs.onNext(file.getName) } } fileObs.addListener(fileListener) fileMonitor.addObserver(fileObs) fileMonitor.start() Subscription { fileMonitor.stop() } } }
  • 31. def hotObserver(directory: String): Observable[String] = { val fileMonitor = new FileAlterationMonitor(1000) val fileObs = new FileAlterationObserver(directory) fileMonitor.addObserver(fileObs) Observable.apply[String] { obs => val fileListener = new FileAlterationListenerAdaptor { override def onFileChange(file: java.io.File): Unit = { obs.onNext(file.getName) } } fileObs.addListener(fileListener) Subscription { fileObs.removeListener( fileListener) } } }
  • 32. val odds = Observable.interval(0.5 seconds) .filter(x => x % 2 == 1) .map(x => s"num $x") .take(5) odds.subscribe(str => println(str))
  • 33. def fetchQuote(): Future[String] = Future { blocking { val url = “http://www.iheartquotes.com/api/v1/random?" + "show_permalink=false&show_source=false" Source.fromURL(url).getLines().mkString } } def fetchQuoteObservable(): Observable[String] = { Observable.from(fetchQuote()) } def quotes(): Observable[Observable[String]] = { Observable.interval(1 second).take(5).map { n => fetchQuoteObservable().map(txt => s"$n) $txt") } } val concat: Observable[String] = quotes().concat concat.subscribe(q => println(q)) / val flatten: Observable[String] = quotes().flatten // val qs: Observable[String] = for { n <- Observable.interval(1 second).take(5) txt <- fetchQuoteObservable() } yield s"$n) $txt" qs.subscribe(q => println(q))
  • 34. def randomQuote() = Observable.apply[String] { obs => val url = "http://www.iheartquotes.com/api/v1/random?" + "show_permalink=false&show_source=false" obs.onNext(Source.fromURL(url).getLines.mkString) obs.onCompleted() Subscription } import Observable._ def errorMessage = items("Retrying...") ++ error(new Exception) def quoteMessage(): Observable[String] = for { text <- randomQuote() message <- if (text.size < 50) items(text) else errorMessage } yield message quoteMessage().retry(5).subscribe(str => println(str))
  • 35. val status = Observable.items("1", "2") ++ Observable.error(new Exception) val fixedStatus = status.onErrorReturn(e => "exception") fixedStatus.subscribe(str => println(str)) val continuedStatus = status.onErrorResumeNext(e => Observable.items("4", "5")) continuedStatus.subscribe(str => println(str))