Swift

[Combine] AsyncPublisher 란?

insub4067 2023. 10. 24. 13:42

struct ContentView: View {
    
    @StateObject var viewModel = ContentViewModel()
    
    var body: some View {
        Button("Button") {
            viewModel.didTap()
        }
    }
}
class ContentViewModel: ObservableObject {
    
    @Published var items: [String] = []
    private var store = Set<AnyCancellable>()
    
    init() {
        observe()
    }
    
    func didTap() {
        items = ["1", "2", "3"]
    }
    
    func observe() {
        Task {
            for await value in $items.values {
                print("values: ", value)
            }
        }
        
        $items
            .receive(on: DispatchQueue.main)
            .sink { value in
                print("sink: ", value)
            }.store(in: &store)
    }
}

 

Publisher 에서 던져주는 값을 sink 가 아닌 async await 으로 받아 올수 있음 !