SwiftUI and RxSwift Observer Closure Behavior - swift

I'm building an iOS app, using RxSwift and SwiftUI. I'm completely new to these frameworks so I was following a few tutorials, but I'm having a hard time figuring how to setup a Observer coupled with SwiftUI whereas I'd like to keep updating my UI as long as my BehaviorRelay list of events is updated, here's what I've got in my UI:
import SwiftUI
import RxSwift
struct EventsTableView: View {
private let observer: EventsTableObserver = EventsTableObserver()
init() {
observer.setObserver()
EventViewModel.getAllEvents()
}
var body: some View {
List{
ForEach(observer.events_view,id: \.id) { event in
HStack {
Text(event.title)
}
}
}
}
}
class EventsTableObserver {
private let disposeBag = DisposeBag()
var events_view = [Event]()
func setObserver(){
EventGroup.shared.events.asObservable()
.subscribe(onNext: {
[unowned self] events in
self.events_view = events
})
.disposed(by: disposeBag)
}
}
The problem is that apparently after my closure ends, self.events_view is not keeping the stored events values as I'd like to, even though the events are being updated. Can someone give me a direction here?

Related

Combine - .sink {..} is called as many times as there are cancellables

I use Combine to track changes in the View Model and react to these changes in the View in the UIKit Application. The thing is that every time the change occurs sink is getting called one more time. I store subscriptions in the Set() and basically sink as called as many times as there are cancellables. If I remove and add items to the cart 5 times the sink would be called 10 times. Is this correct behavior or I'm doing something wrong?
My View Model Protocol:
protocol CartTrackable {
var addedToCart: Bool { get set }
var addedToCartPublisher: Published<Bool>.Publisher { get }
}
My View Model:
final class CartViewModel: ObservableObject, CartTrackable {
#Published var addedToCart = false
var addedToCartPublisher: Published<Bool>.Publisher { $addedToCart }
func addToCart() {
addedToCart = true
}
func removeFromCart() {
addedToCart = false
}
}
And here is the relevant code in my View:
private var cancellables = Set<AnyCancellable>()
func setObserver() {
viewModel?.addedToCartPublisher
.dropFirst()
.receive(on: RunLoop.main)
.sink { [weak self] cartStatus in
self?.addToCartButton.showAnimation(for: cartStatus)
}
.store(in: &cancellables)
}
Declaring cancellable as one object helps - .sink is always called only once, but I keep track of several things, and having separate cancellables for them is just a lot of repeated code. Would love to hear your opinions! Cheers!

Easier way of dealing with CurrentValueSubject

I have a Complex class which I pass around as an EnvironmentObject through my SwiftUI views. Complex contains several CurrentValueSubjects. I don't want to add the Published attribute to the publishers on class Complex, since Complex is used a lot around the views and that will force the views to reload on every published value.
Instead, I want a mechanism which can subscribe to specific publisher which Complex holds. That way, Views can choose on which publisher the view should re-render itself.
The code below works, but I was wondering if there was an easier solution, it feels like a lot of work just to listen to the updates CurrentValueSubject gives me:
import SwiftUI
import Combine
struct ContentView: View {
let complex = Complex()
var body: some View {
PublisherView(boolPublisher: .init(publisher: complex.boolPublisher))
.environmentObject(complex)
}
}
struct PublisherView: View {
#EnvironmentObject var complex: Complex
#ObservedObject var boolPublisher: BoolPublisher
var body: some View {
Text("\(String(describing: boolPublisher.publisher))")
}
}
class Complex: ObservableObject {
let boolPublisher: CurrentValueSubject<Bool, Never> = .init(true)
// A lot more...
init() {
startToggling()
}
func startToggling() {
DispatchQueue.global().asyncAfter(deadline: .now() + 1) { [unowned self] in
let newValue = !boolPublisher.value
print("toggling to \(newValue)")
boolPublisher.send(newValue)
startToggling()
}
}
}
class BoolPublisher: ObservableObject {
private var cancellableBag: AnyCancellable? = nil
#Published var publisher: Bool
init(publisher: CurrentValueSubject<Bool, Never>) {
self.publisher = publisher.value
cancellableBag = publisher
.receive(on: DispatchQueue.main)
.sink { [weak self] value in
self?.publisher = value
}
}
}

How can I replace addObserver with publisher in receiving notifications from NotificationCenter

Currently I am using addObserver method to receive my wished notification in my ObservableObject, from the other hand we can use publisher method to receive wished notification in a View, I like to use publisher method inside my ObservableObject instead of addObserver method, how could I do that? How can I receive/notified the published value from publisher in my class?
import SwiftUI
struct ContentView: View {
#StateObject var model: Model = Model()
var body: some View {
Text("Hello, world!")
.padding()
.onReceive(orientationDidChangedPublisher) { _ in
print("orientationDidChanged! from View")
}
}
}
var orientationDidChangedPublisher = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
class Model: ObservableObject {
init() { orientationDidChangeNotification() }
private func orientationDidChangeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(readScreenInfo), name: UIDevice.orientationDidChangeNotification, object: nil) }
#objc func readScreenInfo() { print("orientationDidChanged! from ObservableObject") }
}
You can use the same publisher(for:) inside your class:
import Combine
class Model: ObservableObject {
var cancellable : AnyCancellable?
init() {
cancellable = NotificationCenter.default
.publisher(for: UIDevice.orientationDidChangeNotification)
.sink(receiveValue: { (notification) in
//do something with that notification
print("orientationDidChanged! from ObservableObject")
})
}
}
There are two ways. First using the Combine framework (don't forget to import Combine), and the other using the usual way.
// Without Combine:
class MyClass1 {
let notification = NotificationCenter.default
.addObserver(forName: UIDevice.orientationDidChangeNotification,
object: nil, queue: .main) { notification in
// Do what you want
let orientationName = UIDevice.current.orientation.isPortrait ? "Portrait" : "Landscape"
print("DID change rotation to " + orientationName)
}
deinit {
NotificationCenter.default.removeObserver(notification)
}
}
// Using Combine
class MyClass2 {
let notification = NotificationCenter.default
.publisher(for: UIDevice.orientationDidChangeNotification)
.sink { notification in
// Do What you want
let orientationName = UIDevice.current.orientation.isPortrait ? "Portrait" : "Landscape"
print("DID change rotation to " + orientationName)
}
deinit {
notification.cancel()
}
}
In deinit you should remove all the observers, like i've shown above.
EDIT:
more about deinit:
deinit is the opposite side of init. It is called whenever your instance of the class is about to be removed from the memory.
If you are using the Combine way, it is fine to don't use deinit because as soon as the instance of the class is removed form the memory, the notification which is of type AnyCancelleable is removed from the memory as well, and that results in the notification being cancelled automatically.
But that automatic cancellation doesnt happen when you are using the normal way, and if you dont remove the observer you added, you'll have multiple observers listening to the notification. For example if you delete the deinit in the MyClass1, you'll see that the "DID change rotation to " is typed more than once (3 times for me) when you are using the class in a SwiftUI view, because the class was initialized more thatn once before the SwiftUI view is stable.

How can I get #AppStorage to work in an MVVM / SwiftUI framework?

I have a SettingsManager singleton for my entire app that holds a bunch of user settings. And I've got several ViewModels that reference and can edit the SettingsManager.
The app basically looks like this...
import PlaygroundSupport
import Combine
import SwiftUI
class SettingsManager: ObservableObject {
static let shared = SettingsManager()
#AppStorage("COUNT") var count = 10
}
class ViewModel: ObservableObject {
#Published var settings = SettingsManager.shared
func plus1() {
settings.count += 1
objectWillChange.send()
}
}
struct ContentView: View {
#StateObject var viewModel = ViewModel()
var body: some View {
VStack {
Button(action: viewModel.plus1) {
Text("\(viewModel.settings.count)")
}
}
}
}
let viewController = UIHostingController(rootView: ContentView())
PlaygroundPage.current.liveView = viewController
Frustratingly, it works about 85% of the time. But 15% of the time, the values don't update until navigating away from the view and then back.
How can I get #AppStorage to play nice with my View Model / MVVM framework?!
Came across this question researching this exact issue. I came down on the side of letting SwiftUI do the heavy lifting for me. For example:
// Use this in any view model you need to update the value
extension UserDefaults {
static func setAwesomeValue(with value: Int) {
UserDefaults.standard.set(value, forKey: "awesomeValue")
}
static func getAwesomeValue() -> Int {
return UserDefaults.standard.bool(forKey: "awesomeValue")
}
}
// In any view you need this value
struct CouldBeAnyView: some View {
#AppStorage("awesomeValue") var awesomeValue = 0
}
AppStorage is just a wrapper for UserDefaults. Whenever the view model updates the value of "awesomeValue", AppStorage will automatically pick it up. The important thing is to pass the same key when declaring #AppStorage. Probably shouldn't use a string literal but a constant would be easier to keep track of?
This SettingsManager in a cancellables set solution adapted from the Open Source ACHN App:
import PlaygroundSupport
import Combine
import SwiftUI
class SettingsManager: ObservableObject {
static let shared = SettingsManager()
#AppStorage("COUNT") var count = 10 {
willSet { objectWillChange.send() }
}
}
class ViewModel: ObservableObject {
#Published var settings = SettingsManager.shared
var cancellables = Set<AnyCancellable>()
init() {
settings.objectWillChange
.sink { [weak self] _ in
self?.objectWillChange.send()
}
.store(in: &cancellables)
}
func plus1() {
settings.count += 1
}
}
struct ContentView: View {
#StateObject var viewModel = ViewModel()
var body: some View {
VStack {
Button(action: viewModel.plus1) {
Text(" \(viewModel.settings.count) ")
}
}
}
}
let viewController = UIHostingController(rootView: ContentView())
PlaygroundPage.current.liveView = viewController
Seems to be slightly less glitchy, but still isn't 100% rock-solid consistent :(
Leaving this here to hopefully inspire someone with my attempt

How do you call a method on a UIView from outside the UIViewRepresentable in SwiftUI?

I want to be able to pass a reference to a method on the UIViewRespresentable (or perhaps it’s Coordinator) to a parent View. The only way I can think to do this is by creating a field on the parent View struct with a class that I then pass to the child, which acts as a delegate for this behaviour. But it seems pretty verbose.
The use case here is to be a able to call a method from a standard SwiftUI Button that will zoom the the current location in a MKMapView that’s buried in a UIViewRepresentable elsewhere in the tree. I don’t want the current location to be a Binding as I want this action to be a one off and not reflected constantly in the UI.
TL;DR is there a standard way of having a parent get a reference to a child in SwiftUI, at least for UIViewRepresentables? (I understand this is probably not desirable in most cases and largely runs against the SwiftUI pattern).
I struggled with that myself, here's what worked using Combine and PassthroughSubject:
struct OuterView: View {
private var didChange = PassthroughSubject<String, Never>()
var body: some View {
VStack {
// send the PassthroughSubject over
Wrapper(didChange: didChange)
Button(action: {
self.didChange.send("customString")
})
}
}
}
// This is representable struct that acts as the bridge between UIKit <> SwiftUI
struct Wrapper: UIViewRepresentable {
var didChange: PassthroughSubject<String, Never>
#State var cancellable: AnyCancellable? = nil
func makeUIView(context: Context) → SomeView {
let someView = SomeView()
// ... perform some initializations here
// doing it in `main` thread is required to avoid the state being modified during
// a view update
DispatchQueue.main.async {
// very important to capture it as a variable, otherwise it'll be short lived.
self.cancellable = didChange.sink { (value) in
print("Received: \(value)")
// here you can do a switch case to know which method to call
// on your UIKit class, example:
if (value == "customString") {
// call your function!
someView.customFunction()
}
}
}
return someView
}
}
// This is your usual UIKit View
class SomeView: UIView {
func customFunction() {
// ...
}
}
I'm sure there are better ways, including using Combine and a PassthroughSubject. (But I never got that to work.) That said, if you're willing to "run against the SwiftUI pattern", why not just send a Notification? (That's what I do.)
In my model:
extension Notification.Name {
static let executeUIKitFunction = Notification.Name("ExecuteUIKitFunction")
}
final class Model : ObservableObject {
#Published var executeFuntionInUIKit = false {
willSet {
NotificationCenter.default.post(name: .executeUIKitFunction, object: nil, userInfo: nil)
}
}
}
And in my UIKit representable:
NotificationCenter.default.addObserver(self, selector: #selector(myUIKitFunction), name: .executeUIKitFunction, object: nil)
Place that in your init or viewDidLoad, depending on what kind of representable.
Again, this is not "pure" SwiftUI or Combine, but someone better than me can probably give you that - and you sound willing to get something that works. And trust me, this works.
EDIT: Of note, you need to do nothing extra in your representable - this simply works between your model and your UIKit view or view controller.
I was coming here to find a better answer, then the one I came up myself with, but maybe this does actually help someone?
It's pretty verbose though nevertheless and doesn't quite feel like the most idiomatic solution, so probably not exactly what the question author was looking for. But it does avoid polluting the global namespace and allows synchronous (and repeated) execution and returning values, unlike the NotificationCenter-based solution posted before.
An alternative considered was using a #StateObject instead, but I need to support iOS 13 currently where this is not available yet.
Excursion: Why would I want that? I need to handle a touch event, but I'm competing with another gesture defined in the SwiftUI world, which would take precedence over my UITapGestureRecognizer. (I hope this helps by giving some context for the brief sample code below.)
So what I came up with, was the following:
Add an optional closure as state (on FooView),
Pass it as a binding into the view representable (BarViewRepresentable),
Fill this from makeUIView,
So that this can call a method on BazUIView.
Note: It causes an undesired / unnecessary subsequent update of BarViewRepresentable, because setting the binding changes the state of the view representable though, but this is not really a problem in my case.
struct FooView: View {
#State private var closure: ((CGPoint) -> ())?
var body: some View {
BarViewRepresentable(closure: $closure)
.dragGesture(
DragGesture(minimumDistance: 0, coordinateSpace: .local)
.onEnded { value in
self.closure?(value.location)
})
)
}
}
class BarViewRepresentable: UIViewRepresentable {
#Binding var closure: ((CGPoint) -> ())?
func makeUIView(context: UIViewRepresentableContext<BarViewRepresentable>) -> BazUIView {
let view = BazUIView(frame: .zero)
updateUIView(view: view, context: context)
return view
}
func updateUIView(view: BazUIView, context: UIViewRepresentableContext<BarViewRepresentable>) {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
strongSelf.closure = { [weak view] point in
guard let strongView = view? else {
return
}
strongView.handleTap(at: point)
}
}
}
}
class BazUIView: UIView { /*...*/ }
This is how I accomplished it succesfully. I create the UIView as a constant property in the SwiftUI View. Then I pass that reference into the UIViewRepresentable initializer which I use inside the makeUI method. Then I can call any method (maybe in an extension to the UIView) from the SwiftUI View (for instance, when tapping a button). In code is something like:
SwiftUI View
struct MySwiftUIView: View {
let myUIView = MKMapView(...) // Whatever initializer you use
var body: some View {
VStack {
MyUIView(myUIView: myUIView)
Button(action: { myUIView.buttonTapped() }) {
Text("Call buttonTapped")
}
}
}
}
UIView
struct MyUIView: UIViewRepresentable {
let myUIView: MKMapView
func makeUIView(context: UIViewRepresentableContext<MyUIView>) -> MKMapView {
// Configure myUIView
return myUIView
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<MyUIView>) {
}
}
extension MKMapView {
func buttonTapped() {
print("The button was tapped!")
}
}