UIKit + Observation

· 1min
Table of Contents

前言

如何在 UIKit 使用 Observation (@Observable)

使用

使用 withObservationTracking(_:onChange:) 即可.
ex:

private func setupBinding() {
    _ = withObservationTracking {
        vm.state
    } onChange: { [weak self] in
        guard let self else { return }
        Task { @MainActor [weak self] in
            guard let self else { return }
            if viewIfLoaded?.window == nil { return }
            
            switch vm.state {
            case .none:
                stateNone()
            case let .dataLoaded(response):
                stateDataLoaded(response: response)
            case let .localSearched(response):
                stateLocalSearched(response: response)
            case let .favoriteChanged(response):
                stateFavoriteChanged(response: response)
            }
            
            setupBinding()
        }
    }
}

因為沒有人持有, 所以最後還需要 call setupBinding()

參考

可參考 Comic 每個 VC 使用方式.