Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created May 23, 2020 19:22
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/854c2844366351e4fe29e91118ebfdbb to your computer and use it in GitHub Desktop.
Save rayfix/854c2844366351e4fe29e91118ebfdbb to your computer and use it in GitHub Desktop.
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