我试图从一个简单的Int创建一个observable,所以我可以在更改时订阅它,但它只监听第一次加载,我错过了什么?提前致谢。
private func startObserving() {
getRating().subscribe(onNext: { (rating: Int) in
print("NAKO \(rating)")
})
}
private func getRating() -> Observable<Int> {
return Observable.create{ observer in
observer.on(.next(self.ratingView.rating()))
observer.on(.completed)
return Disposables.create()
}
}
//
var changingValue = PublishSubject<Int>()
//
// let value = self.ratingView.rating()
// changingValue.onNext(value) // inform observers like so
//
private let disposeBag = DisposeBag()
changingValue.asObservable()
.subscribe(onNext: { [weak self] (value) in
print("NAKO \(value)")
})
.disposed(by: disposeBag)
您需要将评级值转换为值流,如果使用onCompleted,则流将完成,因此无需使用onCompleted。
let rating = self.ratingView.rating()
Observable.of(rating)
.subscribe(onNext: { (value: Int) in
print(value)
})
.disposed(by: disposeBag)
我认为,如果您无权修改原始代码,您唯一能做的就是这样:
class YourRatingView: RatingView {
private let ratingSubject: ReplaySubject<Int>
override var rating: Int {
get { return super.rating }
set {
super.rating = newValue
ratingSubject.on(.next(super.rating))
}
}
override init(){
ratingSubject = ReplaySubject<Int>.create(bufferSize: 1)
super.init()
ratingSubject.on(.next(super.rating))
}
var rating_rx: Observable<Int> {
return ratingSubject.asObservable()
}
}
看看我正在使用ReplaySubject
所以每次订阅时,您至少会收到评级的最后一个值。然后,每次更改后,您都会收到订阅中的活动。
let ratingView = YourRatingView()
ratingView.rating_rx.subscribe(onNext: { rating in
print(rating)
}).disposed(by: disposeBag)