Skip to content

Instantly share code, notes, and snippets.

@rayfix
Last active May 16, 2020 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayfix/f97a8f9bac0bc3ba7d23f64fa4b3dfe1 to your computer and use it in GitHub Desktop.
Save rayfix/f97a8f9bac0bc3ba7d23f64fa4b3dfe1 to your computer and use it in GitHub Desktop.
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