feat(training): 为请求操作接入通用Loading

This commit is contained in:
2026-10-14 18:07:55 +08:00
parent 8c8ba00778
commit ce6cccf2b7
12 changed files with 1396 additions and 44 deletions
@@ -7,6 +7,9 @@ final class TrainingCenterViewController: TrainingBaseViewController {
/// 差异化列表中的任务与考试记录标识。
private enum Item: Hashable { case task(String), attempt(String) }
private var reloadTask: Task<Void, Never>?
private var reloadLoadingToken: UUID?
private var moreTask: Task<Void, Never>?
private var moreLoadingToken: UUID?
private var searchTask: Task<Void, Never>?
private let service: any TrainingDataServing
private let viewModel = TrainingRemoteCenterViewModel()
@@ -184,6 +187,8 @@ final class TrainingCenterViewController: TrainingBaseViewController {
}
override func bindActions() {
retryButton.accessibilityIdentifier = "training.center.retry"
moreButton.accessibilityIdentifier = "training.center.more"
refreshControl.addTarget(self, action: #selector(reloadTapped), for: .valueChanged)
retryButton.addTarget(self, action: #selector(reloadTapped), for: .touchUpInside)
viewAllButton.addTarget(self, action: #selector(viewAllTapped), for: .touchUpInside)
@@ -274,24 +279,67 @@ final class TrainingCenterViewController: TrainingBaseViewController {
}
@objc private func reloadTapped() {
scheduleReload(showsLoading: true)
}
private func releaseReloadLoading() {
if let token = reloadLoadingToken { endRequestLoading(token) }
reloadLoadingToken = nil
}
private func releaseMoreLoading() {
if let token = moreLoadingToken { endRequestLoading(token) }
moreLoadingToken = nil
}
private func scheduleReload(showsLoading: Bool) {
if showsLoading {
searchTask?.cancel()
searchTask = nil
}
reloadTask?.cancel()
reloadTask = Task { @MainActor [weak self] in await self?.reload() }
releaseReloadLoading()
moreTask?.cancel()
moreTask = nil
releaseMoreLoading()
let token = showsLoading ? beginRequestLoading() : nil
reloadLoadingToken = token
reloadTask = Task { @MainActor in
defer {
if let token { endRequestLoading(token) }
if reloadLoadingToken == token { reloadLoadingToken = nil }
}
await reload()
}
}
@objc private func tabTapped(_ button: UIButton) { if let tab = TrainingCenterTab(rawValue: button.tag) { selectTab(tab) } }
@objc private func filterTapped(_ button: UIButton) { viewModel.filter = button.tag == 0 ? .pendingExam : .completed; reloadTapped() }
@objc private func searchChanged() {
viewModel.setKeyword(searchField.text ?? "")
reloadTask?.cancel()
releaseReloadLoading()
moreTask?.cancel()
moreTask = nil
releaseMoreLoading()
searchTask?.cancel()
moreButton.isHidden = true
searchTask = Task { @MainActor [weak self] in
do { try await Task.sleep(for: .milliseconds(300)) } catch { return }
self?.reloadTapped()
self?.scheduleReload(showsLoading: false)
}
}
@objc private func moreTapped() {
Task { @MainActor [weak self] in
guard let self else { return }
guard moreTask == nil, viewModel.hasMore, !viewModel.isLoading, !viewModel.isLoadingMore else { return }
let token = beginRequestLoading()
moreLoadingToken = token
moreTask = Task { @MainActor in
defer {
endRequestLoading(token)
if moreLoadingToken == token {
moreLoadingToken = nil
moreTask = nil
}
}
await viewModel.loadMore(service: service)
if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return }
applyState()
@@ -26,6 +26,13 @@ final class TrainingCourseViewController: TrainingBaseViewController {
private var contentIsReady = false
private var contentLoadFailed = false
private var pageIsVisible = false
private var userRequestID: UUID?
/// 用户操作独占的请求票据;缓存复用仍防重复操作,但不展示全局进度。
private struct UserRequest {
let id: UUID
let loadingToken: UUID?
}
/// 当前任务标识,成绩页可复用已有课程页面。
var taskID: String { viewModel.taskID }
@@ -106,10 +113,16 @@ final class TrainingCourseViewController: TrainingBaseViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
pageIsVisible = true
if viewModel.task == nil { loadCourse() }
else {
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
let previousContent = contentTask
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await previousContent?.value
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self,
userRequestID == nil else { return }
if viewModel.task == nil { loadCourse() }
else if viewModel.currentSection == nil, let id = viewModel.currentSectionID { selectSection(id) }
else {
if contentNavigation == nil { renderCurrentSection() }
await viewModel.refreshProgress()
applyState()
resumeReading()
@@ -120,6 +133,7 @@ final class TrainingCourseViewController: TrainingBaseViewController {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
pageIsVisible = false
contentTask?.cancel()
pauseReading()
}
@@ -131,20 +145,22 @@ final class TrainingCourseViewController: TrainingBaseViewController {
}
private func loadCourse() {
guard let request = beginUserRequest(showsLoading: true) else { return }
pauseReading()
contentIsReady = false
contentLoadFailed = false
contentNavigation = nil
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.load()
guard !Task.isCancelled else { return }
await performUserRequest(request) { await self.viewModel.load() }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
renderCurrentSection()
applyState()
}
}
private func selectSection(_ id: String) {
guard let request = beginUserRequest(showsLoading: !viewModel.isSectionCached(id: id)) else { return }
isOpeningResource = false
pauseReading()
contentIsReady = false
@@ -152,8 +168,8 @@ final class TrainingCourseViewController: TrainingBaseViewController {
contentNavigation = nil
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.selectSection(id: id)
guard !Task.isCancelled else { return }
await performUserRequest(request) { await self.viewModel.selectSection(id: id) }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
renderCurrentSection()
applyState()
}
@@ -186,8 +202,13 @@ final class TrainingCourseViewController: TrainingBaseViewController {
private func applyState() {
guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return }
sectionsButton.isEnabled = !viewModel.isLoading && !viewModel.sections.isEmpty
attachmentsButton.isEnabled = !viewModel.isLoading && (viewModel.course?.attachmentCount ?? 0) > 0
let canInteract = userRequestID == nil
sectionsButton.isUserInteractionEnabled = canInteract
attachmentsButton.isUserInteractionEnabled = canInteract
actionButton.isUserInteractionEnabled = canInteract
guard canInteract else { return }
sectionsButton.isEnabled = !viewModel.sections.isEmpty
attachmentsButton.isEnabled = (viewModel.course?.attachmentCount ?? 0) > 0
if let progress = viewModel.progress, progress.readingCompleted {
noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成"
if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") }
@@ -229,6 +250,26 @@ final class TrainingCourseViewController: TrainingBaseViewController {
actionButton.configuration = configuration
}
private func beginUserRequest(showsLoading: Bool) -> UserRequest? {
guard userRequestID == nil, !viewModel.isInvalidated else { return nil }
let request = UserRequest(id: UUID(), loadingToken: showsLoading ? beginRequestLoading() : nil)
userRequestID = request.id
applyState()
return request
}
private func endUserRequest(_ request: UserRequest) {
if let token = request.loadingToken { endRequestLoading(token) }
guard userRequestID == request.id else { return }
userRequestID = nil
applyState()
}
private func performUserRequest<Value>(_ request: UserRequest, operation: () async -> Value) async -> Value {
defer { endUserRequest(request) }
return await operation()
}
@objc private func pauseReading() {
readingTimer?.invalidate()
readingTimer = nil
@@ -252,9 +293,12 @@ final class TrainingCourseViewController: TrainingBaseViewController {
private func resumeReading(retrying: Bool = false) {
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), readingTask == nil else { return }
let request = retrying ? beginUserRequest(showsLoading: true) : nil
guard !retrying || request != nil else { return }
let pendingClose = closingTask
readingTask = Task { @MainActor [weak self] in
guard let self else { return }
defer { if let request { endUserRequest(request) } }
await pendingClose?.value
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), !Task.isCancelled else {
readingTask = nil
@@ -299,6 +343,7 @@ final class TrainingCourseViewController: TrainingBaseViewController {
}
@objc private func actionTapped() {
guard userRequestID == nil else { return }
if let progress = viewModel.progress, progress.readingCompleted {
pauseReading()
if viewModel.task?.summary.mode == .exam && progress.canStartExam {
@@ -334,13 +379,17 @@ final class TrainingCourseViewController: TrainingBaseViewController {
}
@objc private func sectionsTapped() {
guard userRequestID == nil, !viewModel.sections.isEmpty else { return }
isOpeningResource = true
pauseReading()
let picker = TrainingCoursePickerViewController(title: "章节目录", rows: sectionRows(), hasMore: viewModel.hasMoreSections,
selectedID: viewModel.currentSectionID, select: { [weak self] id in self?.selectSection(id) },
loadMore: { [weak self] in
guard let self else { return ([], false) }
await viewModel.loadMoreSections()
guard viewModel.hasMoreSections, let request = beginUserRequest(showsLoading: true) else {
return (sectionRows(), viewModel.hasMoreSections)
}
await performUserRequest(request) { await self.viewModel.loadMoreSections() }
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (sectionRows(), viewModel.hasMoreSections)
@@ -353,18 +402,22 @@ final class TrainingCourseViewController: TrainingBaseViewController {
}
@objc private func attachmentsTapped() {
guard let request = beginUserRequest(showsLoading: !viewModel.hasLoadedAttachments) else { return }
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.loadAttachments()
guard !Task.isCancelled else { return }
await performUserRequest(request) { await self.viewModel.loadAttachments() }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
if viewModel.isInvalidated { applyState(); return }
if let error = viewModel.errorMessage { isOpeningResource = false; showToast(error); applyState(); return }
let picker = TrainingCoursePickerViewController(title: "课程附件", rows: attachmentRows(), hasMore: viewModel.hasMoreAttachments,
select: { [weak self] id in self?.openAttachment(id) }, loadMore: { [weak self] in
guard let self else { return ([], false) }
await viewModel.loadAttachments(loadMore: true)
guard viewModel.hasMoreAttachments, let request = beginUserRequest(showsLoading: true) else {
return (attachmentRows(), viewModel.hasMoreAttachments)
}
await performUserRequest(request) { await self.viewModel.loadAttachments(loadMore: true) }
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (attachmentRows(), viewModel.hasMoreAttachments)
@@ -387,11 +440,14 @@ final class TrainingCourseViewController: TrainingBaseViewController {
}
private func openAttachment(_ id: String) {
guard let request = beginUserRequest(showsLoading: true) else { return }
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
guard let link = await viewModel.authorizeAttachment(id: id), !Task.isCancelled else {
let link = await performUserRequest(request) { await self.viewModel.authorizeAttachment(id: id) }
guard pageIsVisible, navigationController?.topViewController === self, !Task.isCancelled else { return }
guard let link else {
isOpeningResource = false
if let error = viewModel.errorMessage { showToast(error) }
applyState()
@@ -11,6 +11,7 @@ final class TrainingExamViewController: TrainingBaseViewController {
private var navigationIsScheduled = false
private var hasAppeared = false
private var isPerformingOperation = false
private var requestLoadingToken: UUID?
private var needsReloadOnReturn = false
private var renderedQuestion: TrainingQuestionItem?
private var optionButtons: [String: UIButton] = [:]
@@ -100,7 +101,7 @@ final class TrainingExamViewController: TrainingBaseViewController {
hasAppeared = true
guard !isPerformingOperation, !viewModel.isBusy else { return }
if viewModel.submittedAttempt != nil || viewModel.shouldReturnToCenter {
beginOperation(message: "正在确认考试状态…")
beginOperation(message: "正在确认考试状态…", showsLoading: false)
Task { @MainActor in await viewModel.validateIdentity(); finishOperation() }
return
}
@@ -206,14 +207,19 @@ final class TrainingExamViewController: TrainingBaseViewController {
for button in buttons { button.isUserInteractionEnabled = enabled }
}
private func beginOperation(message: String) {
private func beginOperation(message: String, showsLoading: Bool = true) {
isPerformingOperation = true
if showsLoading { requestLoadingToken = beginRequestLoading() }
setOperationInteractionEnabled(false)
statusLabel.text = message
statusLabel.textColor = AppColor.textSecondary
}
private func finishOperation() {
if let requestLoadingToken {
endRequestLoading(requestLoadingToken)
self.requestLoadingToken = nil
}
isPerformingOperation = false
applyState()
scheduleNavigationIfNeeded()
@@ -13,6 +13,8 @@ final class TrainingResultViewController: TrainingBaseViewController {
private var showsDetails = false
private var usesInitialDetail: Bool
private var resultLoadTask: Task<Void, Never>?
private var isRequestInFlight = false
private var requestLoadingToken: UUID?
private let scrollView = UIScrollView()
private let contentStack = UIStackView()
private let footer = UIView()
@@ -89,8 +91,14 @@ final class TrainingResultViewController: TrainingBaseViewController {
/// 页面出现时只刷新该次成绩,解析在用户展开后加载。
func reload() async {
if let resultLoadTask { await resultLoadTask.value; return }
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews,
!Task.isCancelled else { return }
if leaveInaccessibleTaskIfNeeded() { return }
let token = beginResultRequest()
let task = Task<Void, Never> { @MainActor [weak self] in
await self?.performReload()
guard let self else { return }
defer { finishResultRequest(token) }
await performReload()
}
resultLoadTask = task
await task.value
@@ -98,7 +106,6 @@ final class TrainingResultViewController: TrainingBaseViewController {
}
private func performReload() async {
actionButton.isEnabled = false
await viewModel.load(service: service)
if leaveInaccessibleTaskIfNeeded() { return }
if let detail = viewModel.detail {
@@ -110,7 +117,31 @@ final class TrainingResultViewController: TrainingBaseViewController {
contentStack.addArrangedSubview(TrainingUI.text(viewModel.errorMessage ?? "成绩加载失败", color: TrainingUI.muted))
setActionTitle("重新加载")
}
actionButton.isEnabled = true
}
/// 同步锁定请求动作,Loading 令牌只属于这一次真正发出的请求。
private func beginResultRequest() -> UUID {
isRequestInFlight = true
contentStack.isUserInteractionEnabled = false
actionButton.isUserInteractionEnabled = false
let token = beginRequestLoading()
requestLoadingToken = token
return token
}
/// 成功、失败和取消均释放原令牌,保持按钮正常外观。
private func finishResultRequest(_ token: UUID) {
endRequestLoading(token)
guard requestLoadingToken == token else { return }
requestLoadingToken = nil
isRequestInFlight = false
contentStack.isUserInteractionEnabled = true
actionButton.isUserInteractionEnabled = true
}
/// 导航前主动释放本页请求;离页后的旧 defer 可以安全再次结束同一令牌。
private func finishCurrentRequestBeforeNavigation() {
if let token = requestLoadingToken { finishResultRequest(token) }
}
private func clearContent() {
@@ -120,6 +151,7 @@ final class TrainingResultViewController: TrainingBaseViewController {
private func leaveInaccessibleTaskIfNeeded() -> Bool {
let identityChanged = !validateIdentity() || viewModel.isIdentityInvalid
guard identityChanged || viewModel.isAccessRevoked else { return false }
finishCurrentRequestBeforeNavigation()
clearContent()
if !identityChanged,
let center = navigationController?.viewControllers.first(where: { $0 is TrainingCenterViewController }) {
@@ -169,7 +201,7 @@ final class TrainingResultViewController: TrainingBaseViewController {
let details = TrainingUI.button(showsDetails ? "收起答案解析" : "查看答案解析", secondary: true)
details.accessibilityIdentifier = "training.result.details"
details.addTarget(self, action: #selector(toggleDetails), for: .touchUpInside)
details.isEnabled = attempt.reviewAvailable && !viewModel.isLoadingReviews
details.isEnabled = attempt.reviewAvailable
contentStack.addArrangedSubview(details)
let learning = TrainingUI.button("返回学习", plain: true)
learning.accessibilityIdentifier = "training.result.learning"
@@ -199,7 +231,7 @@ final class TrainingResultViewController: TrainingBaseViewController {
if viewModel.isLoadingReviews { contentStack.addArrangedSubview(TrainingUI.text("正在加载解析…", color: TrainingUI.muted)) }
if viewModel.hasMoreReviews || viewModel.reviewErrorMessage != nil {
let more = TrainingUI.button(viewModel.reviewErrorMessage != nil ? "重试加载解析" : "加载更多解析", plain: true)
more.isEnabled = !viewModel.isLoadingReviews
more.accessibilityIdentifier = "training.result.reviews.more"
more.addTarget(self, action: #selector(moreReviewsTapped), for: .touchUpInside)
contentStack.addArrangedSubview(more)
}
@@ -210,24 +242,31 @@ final class TrainingResultViewController: TrainingBaseViewController {
}
@objc private func toggleDetails() {
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
if leaveInaccessibleTaskIfNeeded() { return }
guard let detail = viewModel.detail else { return }
guard let detail = viewModel.detail, detail.attempt.reviewAvailable else { return }
showsDetails.toggle()
render(detail: detail)
guard showsDetails else { return }
Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.loadReviews(service: service)
if leaveInaccessibleTaskIfNeeded() { return }
if let current = viewModel.detail { render(detail: current) }
}
guard showsDetails, !viewModel.hasLoadedReviews else { return }
loadReviewPage(nextPage: false)
}
@objc private func moreReviewsTapped() {
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
if leaveInaccessibleTaskIfNeeded() { return }
Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.loadReviews(service: service, nextPage: viewModel.hasLoadedReviews)
loadReviewPage(nextPage: viewModel.hasLoadedReviews)
}
/// 首次展开、翻页和失败重试才持有 Loading,已缓存解析切换不发请求。
private func loadReviewPage(nextPage: Bool) {
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews,
viewModel.detail?.attempt.reviewAvailable == true else { return }
if nextPage { guard viewModel.hasMoreReviews else { return } }
else { guard !viewModel.hasLoadedReviews else { return } }
let token = beginResultRequest()
Task { @MainActor in
defer { finishResultRequest(token) }
await viewModel.loadReviews(service: service, nextPage: nextPage)
if leaveInaccessibleTaskIfNeeded() { return }
if let current = viewModel.detail { render(detail: current) }
}
@@ -235,8 +274,10 @@ final class TrainingResultViewController: TrainingBaseViewController {
/// 无论是否通过都能返回本次课程,优先复用导航栈中的课程页面。
@objc private func returnToLearning() {
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
if leaveInaccessibleTaskIfNeeded() { return }
guard viewModel.detail != nil, let navigationController else { return }
finishCurrentRequestBeforeNavigation()
if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) {
navigationController.popToViewController(course, animated: true)
} else {
@@ -245,9 +286,11 @@ final class TrainingResultViewController: TrainingBaseViewController {
}
@objc private func actionTapped() {
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
if leaveInaccessibleTaskIfNeeded() { return }
if loadFailed { loadResult(); return }
guard let detail = viewModel.detail, let navigationController else { return }
finishCurrentRequestBeforeNavigation()
if !detail.attempt.passed, detail.taskState.canRetry {
navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [TrainingExamViewController(taskID: taskID, service: service, resetDraft: true)], animated: true)
} else if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
+30 -2
View File
@@ -281,12 +281,40 @@ final class TrainingRecordCell: UITableViewCell {
/// 培训页面在账号或景区切换时立即关闭,停止展示旧身份记录。
@MainActor
class TrainingBaseViewController: BaseViewController {
private var requestLoadingTokens: Set<UUID> = []
/// 展示本页面请求持有的 App 通用 Loading,在完成或离开页面时释放。
func beginRequestLoading() -> UUID {
let token = GlobalLoadingManager.shared.beginRequest()
requestLoadingTokens.insert(token)
return token
}
/// 只释放本页面持有的令牌,迟到请求不能关闭其它页面的 Loading。
func endRequestLoading(_ token: UUID) {
guard requestLoadingTokens.remove(token) != nil else { return }
GlobalLoadingManager.shared.endRequest(token)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
endOwnedRequestLoading()
}
override func viewDidLoad() {
super.viewDidLoad()
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange] {
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] {
NotificationCenter.default.addObserver(self, selector: #selector(contextChanged), name: name, object: nil)
}
}
@objc private func contextChanged() { navigationController?.popToRootViewController(animated: false) }
private func endOwnedRequestLoading() {
for token in requestLoadingTokens { GlobalLoadingManager.shared.endRequest(token) }
requestLoadingTokens = []
}
@objc private func contextChanged() {
endOwnedRequestLoading()
navigationController?.popToRootViewController(animated: false)
}
}