// 异步 UTF-8 文件读取:在 Console 调用 reader.read(绝对路径),后台 provider 只交付文本,VM worker 执行业务回调。 // owner/key 相同的新读取替换旧任务;失败只记录 Task.error,不执行 apply。 // 持有三个显示对象与当前任务;task 初值占位,第一次 read 后替换为真实 Task。 class FileReader { output: TextBlock problem: TextBlock status: TextBlock task: Object // 仅成功时调用,result 在成功回调期间已可读;写原 TextBlock 触发显示刷新。 function apply(self: FileReader): Unit { self.output.text = self.task.result() } // 以 self 为 owner、file 为 key 启动读取,清空旧输出,并把状态/错误文字绑定到当前任务。 function read(self: FileReader, path: String): Unit { self.task = ui.readText(self, "file", path, self.apply) self.output.text = "" // Task.status/error 是零参数只读方法,可直接作为绑定计算;换任务后绑定也随本次调用更新。 self.status.bind("text", self.task.status) self.problem.bind("text", self.task.error) } } // 先建立界面对象,保持 reader 为可从 Console 操作的全局业务入口。 output = TextBlock("尚未读取文件") problem = TextBlock("") status = TextBlock("") reader = FileReader(output, problem, status, ui.state(0)) page = Page() page.title = "异步文件" page.render(Column(24,16,TextBlock("在 REPL 调用 reader.read(绝对路径字符串)",2),status,output,problem))