Files
endorphin-tessera-gui/examples/async-network.endor
T

43 lines
2.8 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 异步 HTTP(S) 文本 GET:Console 调用 fetcher.fetch(url),沿用 owner/key 替换、状态与成功回调协议。
// 完整响应保存为 String,界面只显示完成提示,避免把可能很大的响应放进文字控件。
// response 是结果业务存储;output/problem/status 仅呈现任务进度与提示。
class TextFetcher {
output: TextBlock
problem: TextBlock
status: TextBlock
// 保存最新请求句柄,owner/key 替换后 apply 只读取当前任务;初始 Object 值尚不是可查询的 Task。
task: Object
// 完整响应留在 VM 业务字段,TextBlock 只显示提示;外部读取和 GUI 排版的内容量分开。
response: String
// 成功后取出完整 UTF-8 结果,写 response 供 Console 查询;provider 失败不会进入此方法。
function apply(self: TextFetcher): Unit {
// 成功交付前调度器已写入 Task 结果;绑定 self 的零参回调在所属 VM 执行,不在网络线程写业务字段。
self.response = self.task.result()
self.output.text = "请求完成;在 REPL 查看 fetcher.response"
}
// 同一 self/request 身份的新请求取消旧交付,重置旧内容并把显示绑定到新任务。
function fetch(self: TextFetcher, url: String): Unit {
// url 来自显式 fetch 调用,HTTP(S) GET 由后台 provider 完成;新句柄返回不代表网络已完成。
self.task = ui.fetchText(self, "request", url, self.apply)
// 只有 fetchText 成功创建新句柄才清旧结果;若 URL 校验/任务额度拒绝,上面的调用报错,下面不会执行。
// 同步清旧结果,避免新请求等待期间让 Console 把旧响应误认成新请求结果。
self.response = ""
self.output.text = ""
// 绑定读取当前 Task 方法,完成和失败由 worker 的任务状态变更传播。
self.status.bind("text", self.task.status)
self.problem.bind("text", self.task.error)
}
}
// 界面不自动访问网络,用户以 Console 明确指定 URL 后才创建任务。
output = TextBlock("尚未请求网络")
// 错误单独绑定 Task.error,即使失败没有调用 apply 也能展示原因。
problem = TextBlock("")
// 进度显示绑定任务状态,响应内容不拼接进这个控件,避免大正文参与每次布局。
status = TextBlock("")
// 全局业务入口让后续 REPL 复用同一 owner,因此多次 fetch 才会按 request 键替换。
fetcher = TextFetcher(output, problem, status, ui.state(0), "")
// Page 展示与任务身份分开,任务归属 fetcher;保持该业务对象可达时,页面隐藏不自动取消它。
page = Page()
page.title = "异步网络"
page.render(Column(24,16,TextBlock("在 REPL 调用 fetcher.fetch(HTTP 或 HTTPS 地址字符串)",2),status,problem,output))