I have a SwiftUI list which presents a detail view/pushes to the navigation when a cell is tapped:
import SwiftUI
struct DevicesInRangeList: View {
@ObservedObject var central = Central()
var body: some View {
NavigationView {
List(central.peripheralsInRange) { peripheral in
NavigationLink(destination: DeviceView(peripheral: peripheral).onAppear {
self.central.connect(peripheral: peripheral)
}.onDisappear {
self.central.disconnect(peripheral: peripheral)
}) {
DeviceRow(deviceID: peripheral.deviceID, name: peripheral.name)
}
}.onAppear {
self.central.scanning = true
}.onDisappear {
self.central.scanning = false
}.navigationBarTitle("Devices in range")
}
}
}
If I tap a row, the detail is displayed. If the peripheral disconnects it is removed from the peripheralsInRange array and the row is removed – but the detail is still displayed. How can the detail be removed when the associated row is removed?
Edit: After Asperi's answer I have the following, which still doesn't work:
struct DevicesInRangeList: View {
@ObservedObject var central = Central()
@State private var localPeripherals: [Peripheral] = []
@State private var activeDetails = false
var body: some View {
NavigationView {
List(localPeripherals, id: \.self) { peripheral in
NavigationLink(destination:
DeviceView(peripheral: peripheral)
.onReceive(self.central.$peripheralsInRange) { peripherals in
if !peripherals.contains(peripheral) {
self.activeDetails = false
}
}
.onAppear {
self.central.connect(peripheral: peripheral)
}
.onDisappear {
self.central.disconnect(peripheral: peripheral)
}
, isActive: self.$activeDetails) {
DeviceRow(deviceID: peripheral.deviceID, name: peripheral.name)
}
}.onReceive(central.$peripheralsInRange) { peripherals in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.localPeripherals = peripherals
}
}.onAppear {
self.central.scanning = true
self.localPeripherals = self.central.peripheralsInRange
}.onDisappear {
self.central.scanning = false
}.navigationBarTitle("Devices in range")
}
}
}