我有Chat
struct Chat {
var id = String()
var gender = String()
var date = Date()
init() {}
}
在视图控制器中,我声明了一个名为observablechat
的聊天实例,然后我使用flatmap运算符尝试仅观察date
observablechat
属性的变化。但是,如果我更改性别属性(如图所示),则会触发订阅。我想知道为什么会这样,我如何修复此代码,以便订阅只查看date
属性会发生什么,而不是其他什么?
class ViewController: UIViewController {
var observablechat = Variable(Chat())
observablechat.asObservable()
.flatMap { (Chat) -> Observable<Date> in
return Observable.of(Chat.matchDate)
}.subscribe(onNext: { (r) in
print(r)
}).addDisposableTo(disposeBag)
self.observablechat.value.gender = "male"
//triggers subscription above.
}
}
答案 0 :(得分:9)
首先,为什么flatMap
?
您只需要distinctUntilChanged
和map
。 DebugPrint
只会被触发两次:初始设置+日期更改一次。查看下面的代码,随时提出问题。
import PlaygroundSupport
import RxSwift
struct Chat {
var id: String
var gender: String
var date: Date
init(id: String = "", gender: String = "", date: Date = Date(timeIntervalSince1970: 0)) {
self.id = id
self.gender = gender
self.date = date
}
}
final class YourClass {
lazy var variableChat: Variable<Chat> = Variable<Chat>(Chat())
var observableDate: Observable<Date> {
return variableChat
.asObservable()
.distinctUntilChanged({ (chatOld, chatNew) -> Bool in
return chatOld.date == chatNew.date
})
.map({ (chat) -> Date in
return chat.date
})
.shareReplay(1)
}
}
let value = YourClass()
value.observableDate
.subscribe(onNext: { (date) in
debugPrint(date.timeIntervalSince1970)
})
value.variableChat.value.gender = "male"
value.variableChat.value.date = Date()
value.variableChat.value.gender = "female"
value.variableChat.value.gender = "male"
value.variableChat.value.gender = "female"
P.S。在操场上运行RxSwift的方法:readme