Last active
May 16, 2020 22:26
-
-
Save rayfix/f97a8f9bac0bc3ba7d23f64fa4b3dfe1 to your computer and use it in GitHub Desktop.
Some SwiftUI/Combine examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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