Search code examples
swiftswiftuicombine

Better way to subscribe to a @published property that changes another @State variable


I have 2 tabbed application where on first tab, it displays a list of grouped media and on second tab you can display more details of the media grid and change some properties of it. For a media group there is a highlighter / thumbnail image the user can pick from elsewhere in the app (2nd tab for example). I'm trying to reflect the change across the UI where the user changes it and it seems very buggy. Looking for a better approach. Thanks in advance.


struct MediaItemView: View {
  @State private var loadedThumbnail: Image?
  @ObservedObject var model: MediaGroup

  var body: View {
    ZStack {
      // show image and other information
    }.task {
      if let thumbMedia = model.thumbnail {
        imageLoader.load(thumbMedia) { thumbnail in
          self.loadedThumbnail = thumbnail
        }
      }
    }

  }

}

// Model

class MediaGroup: ObservableObject {
  @Published var thumbnaill: UUID  // id of the media
}


When the user changes the thumbnail of the model, I set it and fires model.objectWillChange.send() message. But because the state variable is calculated upon entry through a task { ... } it does not capture any future changes.

I currently am using a NotificationCenter notification to force reloaded this on view level, but I'm looking into a better way to propergate the changes using combine frame but am not sure how to do it. Can someone provide some ideas for it?


Solution

  • You could try a different approach to using NotificationCenter and Combine, with

    .onChange(of: model.thumbnaill) { 
    
    }
    

    to listen to changes in your model.thumbnaill and execute some code.