Reputation: 731
I have 2 asynchronous return values from 2 different classes, one from HealthKit, the other from MotionManager. My goal is to combine these values and output them in a swiftui View, where it refreshes every second. I know I have to look at the combine framework here, but I don't know where to start. I can't find a lot of tutorials which describe Swiftui + Combine. I know I have to look at .combineLatest but do I have to write my own Publisher and Subscriber, or can I use @Published property wrapper I have here (@Published var motionData = MotionData() and @Published var heartRateValue: Double = 0.0) ?
My MotionManager Class:
struct MotionValues {
var rotationX: Double = 0.0
var rotationY: Double = 0.0
var rotationZ: Double = 0.0
var pitch: Double = 0.0
var roll: Double = 0.0
var yaw: Double = 0.0
}
class MotionManager: ObservableObject {
@Published var motionValues = MotionValues()
private let manager = CMMotionManager()
func startMotionUpdates() {
manager.deviceMotionUpdateInterval = 1.0
manager.startDeviceMotionUpdates(to: .main) { (data, error) in
guard let data = data, error == nil else {
print(error!)
return
}
self.motionValues.rotationX = data.rotationRate.x
self.motionValues.rotationY = data.rotationRate.y
self.motionValues.rotationZ = data.rotationRate.z
self.motionValues.pitch = data.attitude.pitch
self.motionValues.roll = data.attitude.roll
self.motionValues.yaw = data.attitude.yaw
}
}
func stopMotionUpdates() {
manager.stopDeviceMotionUpdates()
resetAllMotionData()
}
func resetAllMotionData() {
self.motionValues.rotationX = 0.0
self.motionValues.rotationY = 0.0
self.motionValues.rotationZ = 0.0
self.motionValues.pitch = 0.0
self.motionValues.roll = 0.0
self.motionValues.yaw = 0.0
}
}
My HealthKitManager Class:
class HealthKitManager: ObservableObject {
private var healthStore = HKHealthStore()
private var heartRateQuantity = HKUnit(from: "count/min")
private var activeQueries = [HKQuery]()
@Published var heartRateValue: Double = 0.0
func autorizeHealthKit() {
let heartRate = HKObjectType.quantityType(forIdentifier: .heartRate)!
let heartRateVariability = HKObjectType.quantityType(forIdentifier: .heartRateVariabilitySDNN)!
let HKreadTypes: Set = [heartRate, heartRateVariability]
healthStore.requestAuthorization(toShare: nil, read: HKreadTypes) { (success, error) in
if let error = error {
print("Error requesting health kit authorization: \(error)")
}
}
}
func fetchHeartRateData(quantityTypeIdentifier: HKQuantityTypeIdentifier ) {
let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = {
query, samples, deletedObjects, queryAnchor, error in
guard let samples = samples as? [HKQuantitySample] else {
return
}
self.process(samples, type: quantityTypeIdentifier)
}
let query = HKAnchoredObjectQuery(type: HKObjectType.quantityType(forIdentifier: quantityTypeIdentifier)!, predicate: devicePredicate, anchor: nil, limit: HKObjectQueryNoLimit, resultsHandler: updateHandler)
query.updateHandler = updateHandler
healthStore.execute(query)
activeQueries.append(query)
}
private func process(_ samples: [HKQuantitySample], type: HKQuantityTypeIdentifier) {
for sample in samples {
if type == .heartRate {
DispatchQueue.main.async {
self.heartRateValue = sample.quantity.doubleValue(for: self.heartRateQuantity)
}
}
}
}
func stopFetchingHeartRateData() {
activeQueries.forEach { healthStore.stop($0) }
activeQueries.removeAll()
DispatchQueue.main.async {
self.heartRateValue = 0.0
}
}
}
I started with creating a combinedViewModel but I'm stuck here and don't know if this is the way to go:
class CombinedViewModel: ObservableObject {
@Published var motionManager: MotionManager = MotionManager()
@Published var healthManager: HealthKitManager = HealthKitManager()
var anyCancellable: AnyCancellable?
init() {
anyCancellable = Publishers
.CombineLatest(motionManager.$motionValues,healthManager.$heartRateValue)
.sink(receiveValue: {
// Do something
}
})
}
}
Where do I need to focus ? Do I need to learn the combine framework completely to write my own publishers and subscribers, or is there something available with @Published that can do the job ? Or do I need to go for another approach with my CombinedViewModel?
added contentView for reference:
struct ContentView: View {
@State var isActive: Bool = false
private var motion = MotionManager()
private var health = HealthKitManager()
@ObservedObject var combinedViewModel = CombinedViewModel(managerOne: motion, managerTwo: health)
private var motionValues: MotionValues {
return combinedViewModel.combinedValues.0
}
private var heartRateValue: Double {
return combinedViewModel.combinedValues.1
}
var body: some View {
ScrollView {
VStack(alignment: .leading) {
Indicator(title: "X:", value: motionValues.rotationX)
Indicator(title: "Y:", value: motionValues.rotationY)
Indicator(title: "Z:", value: motionValues.rotationZ)
Divider()
Indicator(title: "Pitch:", value: motionValues.pitch)
Indicator(title: "Roll:", value: motionValues.roll)
Indicator(title: "Yaw:", value: motionValues.yaw)
Divider()
Indicator(title: "HR:", value: heartRateValue)
}
.padding(.horizontal, 10)
Button(action: {
self.isActive.toggle()
self.isActive ? self.start() : self.stop()
}) {
Text(isActive ? "Stop" : "Start")
}
.background(isActive ? Color.green : Color.blue)
.cornerRadius(10)
.padding(.horizontal, 5)
}.onAppear {
self.health.autorizeHealthKit()
}
}
private func start() {
self.motion.startMotionUpdates()
self.health.fetchHeartRateData(quantityTypeIdentifier: .heartRate)
}
private func stop() {
self.motion.stopMotionUpdates()
self.health.stopFetchingHeartRateData()
}
}
Upvotes: 0
Views: 775
Reputation: 7591
You can create a new publisher (I would recommend an AnyPublisher
) in your CombinedViewModel
that combines the output from both. Here's a simplified version of your code with a CombinedViewModel
:
class ManagerOne {
@Published var someValue = "Some Value"
}
class ManagerTwo {
@Published var otherValue = "Other Value"
}
class CombinedViewModel {
var combinedPublisher: AnyPublisher<(String, String), Never>
init(managerOne: ManagerOne, managerTwo: ManagerTwo) {
combinedPublisher = managerOne.$someValue
.combineLatest(managerTwo.$otherValue)
.eraseToAnyPublisher()
}
}
If you need CombinedViewModel
to be an observed object you would adapt the code to be more like this:
class CombinedViewModel: ObservableObject {
@Published var combinedValue: (String, String) = ("", "")
var cancellables = Set<AnyCancellable>()
init(managerOne: ManagerOne, managerTwo: ManagerTwo) {
managerOne.$someValue
.combineLatest(managerTwo.$otherValue)
.sink(receiveValue: { [weak self] combined in
self?.combinedValue = combined
})
.store(in: &cancellables)
}
}
A side note about this:
@Published var motionManager: MotionManager = MotionManager()
@Published var healthManager: HealthKitManager = HealthKitManager()
Since both of these managers are classes, $motionManager
and $healthManager
will only emit values when you assign a new instance of MotionManager
or HealthKitManager
to them. Not when a property of either manager changes.
Upvotes: 1