This commit is contained in:
JinJiangHuang
2026-03-03 12:28:02 +08:00
parent aebf17dfb5
commit 76ed32ccf3
7 changed files with 568 additions and 149 deletions
+63 -4
View File
@@ -1,5 +1,6 @@
import Foundation
import SwiftUI
import Combine
/// ViewModel
@MainActor
@@ -19,12 +20,16 @@ class LiveViewModel: ObservableObject {
/// TV
@Published var showChannelList = false
///
private var cancellables: Set<AnyCancellable> = []
init() {
bindLiveChannelGroups()
}
///
func loadChannels() {
self.channelGroups = ApiConfig.shared.liveChannelGroupList
if let firstGroup = channelGroups.first, let firstChannel = firstGroup.channels.first {
currentChannel = firstChannel
}
applyChannelGroups(ApiConfig.shared.liveChannelGroupList)
}
///
@@ -90,6 +95,60 @@ class LiveViewModel: ObservableObject {
//
epgList = []
}
private func bindLiveChannelGroups() {
ApiConfig.shared.$liveChannelGroupList
.sink { [weak self] groups in
self?.applyChannelGroups(groups)
}
.store(in: &cancellables)
}
private func applyChannelGroups(_ groups: [LiveChannelGroup]) {
let previousChannelId = currentChannel?.id
channelGroups = groups
guard !groups.isEmpty else {
selectedGroupIndex = 0
selectedChannelIndex = 0
currentChannel = nil
return
}
if let previousChannelId,
let located = locateChannel(withId: previousChannelId, in: groups) {
selectedGroupIndex = located.groupIndex
selectedChannelIndex = located.channelIndex
currentChannel = groups[located.groupIndex].channels[located.channelIndex]
return
}
let clampedGroupIndex = min(max(0, selectedGroupIndex), groups.count - 1)
selectedGroupIndex = clampedGroupIndex
let channels = groups[clampedGroupIndex].channels
guard !channels.isEmpty else {
selectedChannelIndex = 0
currentChannel = nil
return
}
let clampedChannelIndex = min(max(0, selectedChannelIndex), channels.count - 1)
selectedChannelIndex = clampedChannelIndex
currentChannel = channels[clampedChannelIndex]
}
private func locateChannel(
withId channelId: String,
in groups: [LiveChannelGroup]
) -> (groupIndex: Int, channelIndex: Int)? {
for (groupIndex, group) in groups.enumerated() {
if let channelIndex = group.channels.firstIndex(where: { $0.id == channelId }) {
return (groupIndex, channelIndex)
}
}
return nil
}
}
// 访