Skip to content

Instantly share code, notes, and snippets.

@sidepelican
Created June 10, 2019 22:49
Show Gist options
  • Save sidepelican/2d17f7d8d77d68b7da5644aeec422bfc to your computer and use it in GitHub Desktop.
Save sidepelican/2d17f7d8d77d68b7da5644aeec422bfc to your computer and use it in GitHub Desktop.
BindableObjectのdidChangeは毎回同じものを返してね
import Combine
import SwiftUI
class MyPublisher<T, E>: Publisher where E: Error {
func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input {
inner.receive(subscriber: subscriber)
Swift.print(#function, #line)
}
typealias Output = T
typealias Failure = E
var inner: AnyPublisher<T, E>
init(_ inner: AnyPublisher<T, E>) {
self.inner = inner
Swift.print(#function, #line)
}
deinit {
Swift.print(#function, #line)
}
}
class ContentViewModel: BindableObject {
// ↓こちらだと動く
// let didChange = PassthroughSubject<ContentViewModel, Never>()
// ↓こちらはselectionなどで別途更新をかけないと動かない
// lazy var didChange: MyPublisher<ContentViewModel, Never> = MyPublisher(didChangeSubject.eraseToAnyPublisher())
var didChange: MyPublisher<ContentViewModel, Never> {
MyPublisher(didChangeSubject.eraseToAnyPublisher())
}
private let didChangeSubject = PassthroughSubject<ContentViewModel, Never>()
var objects: [String] {
(0...100).map(String.init)
}
var selected: String? {
didSet {
// didChange.send(self)
didChangeSubject.send(self)
}
}
}
struct ContentView : View {
@ObjectBinding var viewModel: ContentViewModel
var body: some View {
List(viewModel.objects.identified(by: \.self), action: { o in
self.viewModel.selected = o
}) { o in
Text(o)
.background(self.viewModel.selected == o ? Color.red : Color.white)
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView(viewModel: ContentViewModel())
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment