Resolved: How to handle asynchronous API response in scala

In this post, we will see how to resolve How to handle asynchronous API response in scala


I have an API that I need to query in scala. API returns a code that would be equal to 1 when results are ready.
I thought about an until loop to handle as the following:
But this code returns:
So I thought about doing the following:
And it works. But I would like to know if this is really the best scala-friendly way to do so ? How can I properly use a variable that outside of an until loop ?

Best Answer:

When you say API, do you mean you use a http api and you’re using a http library in scala, or do you mean there’s some class/api written up in scala? If you have to keep checking then you have to keep checking I suppose.
If you’re using a Scala framework like Akka or Play, they’d have solutions to asyncrhonously poll or schedule jobs in the background as a part of their solutions which you can read about.
If you’re writing a Scala script, then from a design perspective I would either run the script every 1 minute and instead of having the while loop I’d just quit until code = 1. Otherwise I’d essentially do what you’ve done.
Another library that could help a scala script might be fs2 or ZIO which can allow you to setup tasks that periodically poll.
This appears to be a very open question about designing apps which do polling. A specific answer is hard to give.

If you have better answer, please add a comment about this, thank you!