【发布时间】:2021-03-14 22:34:21
【问题描述】:
轮询和 API 的 Scala 最佳实践是什么?
我正在尝试编写一个轮询 API 的 Scala 方法,检查它是否到达"SUCCESS"。在轮询时,它也可能达到像 "FAILED" 或 "TIMEOUT 这样的错误状态。
在 Java 中,我会这样写:
public String pollEndpoint() {
boolean isPolling = true;
String result = "NA";
while (isPolling) {
Response response = getResponse("http://myAPI.com/ready?id=1234");
if (response.status == "FAILED") { throw new FailedException(response.reason);}
else ... //Some other bad conditions
else if (response.status == "SUCCESS") {
isPolling = false;
result = response.result;
}
System.out.println("Current state is " + response.status); // When running, will be "RUNNING"
Thread.sleep(1000);
}
}
在 Scala 中我可以做到:
def pollEndpoint():String = {
var isPolling = true
var result = "NA"
while (isPolling) {
val response = getResponse("http://myAPI.com/ready?id=1234")
if (response.status == "FAILED") { throw new FailedException(response.reason)}
else ... //Some other bad conditions
else if (response.status == "SUCCESS") {
isPolling = false
result = response.result
}
println("Current state is " + response.status); // When running, will be "RUNNING"
Thread.sleep(1000)
}
}
但是这个解决方案使用vars。
有什么好的方法可以做到这一点,只使用vals?
【问题讨论】:
-
任何
while循环都可以重写为一个简单的尾递归函数,基本上你会收到isPolling作为这样一个函数的参数。 - 但是,在这种特定情况下,进行 API 调用 Async 并使用某种 Stream (如AkkaStreams或 @ 987654331@) 用于管理轮询率和重试逻辑。