我开始使用 ReactiveCocoa,但我仍在为一些基本概念而苦苦挣扎:
- 我的应用程序开始监听地理位置数据(在我的 View 模型中为
init
) - 我的应用程序会发出带有我当前位置的信号(
didFindCurrentPosition
被调用) - 我的 View Controller 显示 map 加载(
viewDidLoad
在我的 View Controller 中) - 我的 View Controller 开始观察当前位置信号(仍然是
viewDidLoad
)
我的问题是:完成第 2 步后,如果没有其他事件发送到信号上,我的 View Controller 就不会收到通知。
我的 View Controller 如何访问信号的最后一个值? (即如何在第 3 步访问第 2 步发出的值?)
感谢您的帮助。
PS:ReactiveCocoa 看起来像一个很棒的库,但我对文档的状态感到困惑。恕我直言,它不是很清楚,也缺乏一些关于如何使用它的明确指南。
代码
View 模型:
class MyViewModel: LocationManagerDelegate {
let locationManager: LocationManager
let geolocationDataProperty = MutableProperty<Geolocation?>(nil)
let geolocationData: Signal<Geolocation?, NoError>
init() {
geolocationData = geolocationDataProperty.signal
// Location Management
locationManager = LocationManager()
locationManager.delegate = self
locationManager.requestLocation()
}
// MARK: - LocationManagerDelegate
func didFindCurrentPosition(location: CLLocation) {
geolocationDataProperty.value = Geolocation(location: location)
}
}
View Controller :
class MyViewController: UIViewController {
let viewModel = MyViewModel()
init() {
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel.geolocationData
.observe(on: UIScheduler())
.observeValues { geolocation in
debugPrint("GOT GEOLOCATION")
}
}
}
最佳答案
您已经有一个 Property
保存最新发出的值。不使用属性的 signal
,而是使用 producer
。这样,当您启动 producer
时,您将首先获得当前值(如果没有发送,您将获得 nil)。
比照。 the documentation :
The current value of a property can be obtained from the value getter. The producer getter returns a signal producer that will send the property’s current value, followed by all changes over time. The signal getter returns a signal that will send all changes over time, but not the initial value.
因此,关于问题中的代码,viewDidLoad
方法应该执行如下操作:
viewModel.geolocationDataProperty
.producer
.start(on: UIScheduler())
.startWithValues { geolocation in
debugPrint("GOT GEOLOCATION")
}
关于ios - 信号观察者能否访问 ReactiveCocoa 信号的最后发射值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44813334/