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