Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some SwiftUI/Combine examples
//
// ContentView.swift
// Pub
//
// Created by Ray Fix on 5/16/20.
// Copyright © 2020 Ray Fix. All rights reserved.
//
import SwiftUI
import Combine
final class ViewModel: ObservableObject {
@Published var number: CGFloat = 9
// The manual way to do @Published
// {
// willSet {
// objectWillChange.send()
// }
// }
// This gets synthesize by the ObservableObject protocol
// let objectWillChange = PassthroughSubject<Void, Never>()
var roundedNumberString: String {
String(describing: Int(number.rounded()))
}
@Published var buzz: Int = 0
var subscriptions = Set<AnyCancellable>()
// View models tend to put a lot in the initializer
init() {
$number
.map { Int($0.rounded()) }
.removeDuplicates()
.filter { $0.isMultiple(of: 5) }
.handleEvents(receiveOutput: { value in
// You can put a side effect in here
print("BUZZ \(value)")
})
.assign(to: \.buzz, on: self)
.store(in: &subscriptions)
}
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
VStack {
Slider(value: $viewModel.number, in: 1...20)
Text(viewModel.roundedNumberString)
Text("\(viewModel.buzz)")
}.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment