我有一个玩家列表,我希望观察每个玩家的耐力,并且观察者应该是相同的。 (也许分享观察员)
class Player {
var stamina = Variable(10)
}
let player1 = Player()
let player2 = Player()
var playerList = Variable([player1, player2])
所以,每当player1.stamina == 0,我就可以从列表中删除player1,现在只能观察到player2。
答案 0 :(得分:-1)
您可以使用Observable.combineLatest将所有最新事件合并到数组元素的属性
这是适合我的解决方案。
class Player {
let stamina = Variable(0)
}
// ViewController
let disposeBag = DisposeBag()
// Array
let playerList: Variable<[Player]> = Variable([])
// Observing each player stamina at once
playerList.asObservable()
.flatMapLatest { players -> Observable<[Int]> in
let playerStaminaObservableList = players.map { $0.stamina.asObservable() }
return Observable.combineLatest { playerStaminaObservableList }
}
.subscribe(onNext: {
print("List of playerStamina: \($0)")
})
.disposed(by: disposeBag)
随意纠正任何错误。