0

So I have an api request that requests a bunch of data from a fake api url, the data I am getting is being put on a placeholder, I just want to have a global variable to be able to use that array of codable data in my collectionviews.

   struct productsList{
        static var itemsList = [ProductItem]()
    
    }
    func getProducts() {
        storeRepo
            .getAllProducts()
            .subscribe { result in
                productsList.itemsList = result
                for item in productsList.itemsList{
                    print(item.category)
                }
            } onError: { error in
                print(error.localizedDescription)
            }.disposed(by: disposeBag)
    }
    func printReuslt() {
        for i in productsList.itemsList{
            print(i.id)
        }
    }

note that it's not printing the printResult() but it's looping inside of the .subscribe

note that i am using Moya as well as RXswift

General Grievance
  • 4,555
  • 31
  • 31
  • 45

1 Answers1

0

What you're looking for is called a Singleton. Swift makes this extremely easy to do. Basically, the short and sweet is that the struct you create, initializes itself as a property of itself. Anytime you access (In this example) APIHandler.shared you'll get a reference to the only single object, which has your other properties dataObj1 and someObj2 from this example.

   class APIHandler {
        let shared = APIHandler()
        var dataObj1: YourObj?
        var someObj2: YourObj2?
    
        init() {
             self.someObj1 = yourMethodCall()
             self.someObj2 = someCalculation()
        }
    }

This is how you access it from another class. BE CAREFUL you can access APIHandler.someObj which would result in a null reference exception if you don't have an object created, so when doing this always access the shared property.

class MainClass {
     let apiHandler: APIHandler?

      override func viewDidLoad(...) {
          super.viewDidLoad(...)
          apiHandler = APIHandler.shared
      }
}
xTwisteDx
  • 2,152
  • 1
  • 9
  • 25
  • A mutable struct singleton probably will not behave the way you expect. Each caller to `APIHandler.shared` will have its own copy of APIHandler, and changes to the properties will not be reflected in other copies. A "singleton" implies that the type has identity; that there is a way to tell the difference between instances, even if they have the same property values. That means it should be a reference type (a class). – Rob Napier Sep 05 '21 at 15:32
  • 1
    Really good call-out on that Rob, I'll update shortly with a more appropriate answer. I hadn't considered that we'd get a new one with each call. – xTwisteDx Sep 07 '21 at 16:06