What is the best approach to handle this case: `lo...
# arrow
m
What is the best approach to handle this case:
loadURL().flatMap { url -> callWS(url) }.flatMap { saveResulte(url: ???, response: it) }
How can I get the url to save it in the last flatMap ? Should I use a pair in the second flatmap
.flatMap { url -> callWS(url).map { Pair(it, url) } }
?
j
Using fx blocks instead of flatMap chains: (in what monad are you? IO?
Copy code
fx {
  val url = loadURL().bind()
  val resp = callWS(url).bind()
  saveResult(url, resp).bind()
}
or similar depending on your code ^^
Making a pair also works, but makes weird code as you need to do all the plumbing
m
I use only
Try
at this moment
Currently, I use the monad Try to catch java exception (when I call java lib).
j
You should probably use
IO
because
Try
will probably be removed soon (we deprecated it a while ago). Anyway this works the same for any monad, but not all have an ext method called
fx
so for
Try
you can do
Try.monad().fx.monad {...}
to get the same thing
s
One of the laws behind flatMap also allows you to safely change it to the following:
Copy code
loadURL().flatMap { url -> callWS(url).flatMap { saveResulte(url, it) } }
This allows you to close over the
url
variable by calling flatMap against the result of
callWS
rather than the result of the first flatMap.
j
that also works, but I find using
fx
blocks leads to more readable code. It's a style thing and I am so used to
fx
that I did not even think of your solution 😄 With arrow-meta those will also have the same runtime representation, but thats a few months out ^^
s
Yep, I'll take preference for the
fx
version too
m
I'll try the fx version, thanks for your help!