Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created May 23, 2020
Embed
What would you like to do?
Some example of using observable object
import SwiftUI
import Combine
final class ViewModel: ObservableObject {
var subs: Set<AnyCancellable> = []
// For some reason this does not work!
init() {
$message.filter { $0.count > 20 }
.print()
.map { String($0.prefix(20)) }
.print()
.assign(to: \.message, on: self)
.store(in: &subs)
}
@Published var message = "Message"
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
VStack {
Text(viewModel.message)
TextField("", text: $viewModel.message)
.textFieldStyle(RoundedBorderTextFieldStyle())
}.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment