Search code examples
arraysswiftrx-swiftmoya

how to change value in struct globally in swift


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


Solution

  • 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
          }
    }