简体   繁体   中英

sink() is not called in combine swift

I have LocationManager class that works well. This is part of LocationManager class.

  var headingDegree = PassthroughSubject<Double, Never>()

  func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    headingDegree.send(-newHeading.magneticHeading)
  }

headingDegree is the value I want to send to my ViewModel. I debugged it to make sure it has correct values, and it does.

So, in my view model,

class CompassViewViewModel: ObservableObject {
 @Published var degree: Double = 0.0
 @State var cancellable = Set<AnyCancellable>()

 func update() {
    LocationManager.shared.headingDegree.sink {
      self.degree = $0
    }
    .store(in: &cancellable)
  }

I sinked my headingDegree . This is the part that brings my problems. If I put breakpoints in update() function, self.degree = $0 is never called.

This is how my View looks like.

struct CompassView: View {
  @ObservedObject var viewModel: CompassViewViewModel

  init(viewModel: CompassViewViewModel) {
    self.viewModel = viewModel
  }

 var body: some View {
    ZStack {
      Text("aa")
        .font(.footnote)
    }
      .onAppear {
        self.viewModel.update()
    }
  }
}

Could you tell me why my sink() is not called?

我将@State var cancellable = Set<AnyCancellable>()更改为private var cancellable = Set<AnyCancellable>()并且效果很好。

Update

in swiftUI1, viewDidLoad in UIHostingcontroller isn't called.


when using combine, with UIKit, subscribing (Sink) in viewDidload, didn't work, instead, subscribe in viewDidAppear

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM