admin管理员组

文章数量:1336367

I have a view model, that has a network service that returns us a Combine publisher. The VM reacts to this publisher by updating its state. And the UIViewController would then update based on the VM state change. This was the setup for UIKit.

Now I am introducing SwiftUI views. I am new to swift UI and not sure how to use the VM's state publisher in SwiftUI. The VM's state is a CurrentValueSubject right now.

Thanks in advance.

I have a view model, that has a network service that returns us a Combine publisher. The VM reacts to this publisher by updating its state. And the UIViewController would then update based on the VM state change. This was the setup for UIKit.

Now I am introducing SwiftUI views. I am new to swift UI and not sure how to use the VM's state publisher in SwiftUI. The VM's state is a CurrentValueSubject right now.

Thanks in advance.

Share Improve this question asked Nov 19, 2024 at 23:57 iOSeriOSer 2842 silver badges14 bronze badges 6
  • Show a minimal reproducible code that produces your issue, see: minimal code. Show the code you have tried, what does not work and the full error message if any. – workingdog support Ukraine Commented Nov 20, 2024 at 0:06
  • Research ObservabeObject @Published and assign from Combine – lorem ipsum Commented Nov 20, 2024 at 1:22
  • See Monitoring data it gives you some good examples of how to manage data in your app. If you are targeting ios17+, have a look at this link Managing model data in your app – workingdog support Ukraine Commented Nov 20, 2024 at 1:31
  • In SwiftUI the View structs are view models so just make a View struct with the data from combine and set it as the rootView anytime it changes – malhal Commented Nov 20, 2024 at 8:52
  • Thanks everyone for the responses. I figured out the solution right after I posted this here. You know how it is when you are reading through a lot of new concepts. – iOSer Commented Nov 20, 2024 at 17:35
 |  Show 1 more comment

1 Answer 1

Reset to default -1

SwiftUI uses the @StateObject or @ObservedObject property wrapper to observe changes in the ViewModel. To enable this, conform your ViewModel to ObservableObject and use a @Published property to represent the state.

Since you already have a CurrentValueSubject in your ViewModel, you can connect it to a @Published property.

本文标签: mvvmHow do I refresh my SwiftUI to changes in my view modelStack Overflow