Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composing Future and Try

This is a follow-up to my previous question

Suppose I have a function, which returns a Future[String], and a function String => Try[Int]:

val slowAsync : Int => Future[String] = ...
val mayFail   : String => Try[Int] = ...

Suppose I am composing them to make a new function Int => Future[Int]:

val composed : Int => Future[Int] = {x => 
  for (str <- slowAsync(x); y <- Future(mayFail(s).get)) yield y
} 

The composed is probably working but I don't like this Future(mayFail(s).get). How would you fix it?

like image 205
Michael Avatar asked Jul 29 '26 20:07

Michael


1 Answers

You can use fromTry:

val x = slowAsync(1) flatMap (s => Future.fromTry(mayFail(s)))
like image 195
seanmcl Avatar answered Aug 02 '26 13:08

seanmcl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!