Skip to content

Commit

Permalink
Use 'weak' for references captured by closures (#222)
Browse files Browse the repository at this point in the history
* Weak-ref in all closures

* Spawn many tasks
  • Loading branch information
daniel-statsig authored Nov 29, 2023
1 parent b4016d6 commit 971fd08
Show file tree
Hide file tree
Showing 8 changed files with 88 additions and 14 deletions.
2 changes: 2 additions & 0 deletions Sample/App/Examples/ExampleDirectoryViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ let Examples: [(String, UIViewController)] = [
( "Basic (ObjC)", BasicViewControllerObjC() ),
( "Perf (ObjC)", PerfViewControllerObjC() ),
( "Many Gates (SwiftUI)", ManyGatesSwiftUIViewController() ),
( "Many Updates (Swift)", ManyUpdatesViewController() ),

]


Expand Down
64 changes: 64 additions & 0 deletions Sample/App/Examples/ManyUpdatesViewController.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import UIKit
import Statsig

class ManyUpdatesViewController: UIViewController {

var queues: [DispatchQueue] = []

override func viewDidLoad() {
super.viewDidLoad()

view.backgroundColor = UIColor.white

let user = StatsigUser(userID: "a-user")
let opts = StatsigOptions(enableCacheByFile: true)

Statsig.start(
sdkKey: Constants.CLIENT_SDK_KEY,
user: user,
options: opts
) { [weak self] err in
if let err = err {
print("Error \(err)")
}

self?.addButton()
}
}

private func addButton() {
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 100, width: 200, height: 50)
button.setTitle("Click", for: .normal)
button.addTarget(self, action: #selector(runUpdates), for: .touchUpInside)
view.addSubview(button)
}

@objc private func runUpdates() {
let numberOfTasks = 10

if (queues.isEmpty) {
for i in 0..<numberOfTasks {
queues.append(DispatchQueue(label: "com.statsig.task_\(i)"))
}
}

for i in 0..<numberOfTasks {
let queue = queues[i]

queue.async {
let user = self.getRandomUser()
print("Updating user \(user.userID ?? "")...")
Statsig.updateUser(user) { err in
print("Updated user \(user.userID ?? "")")
print("Gate check \(Statsig.checkGate("partial_gate"))")
}
}
}
}

private func getRandomUser() -> StatsigUser {
StatsigUser(userID: "user_\(Int.random(in: 1...100))")
}
}

4 changes: 4 additions & 0 deletions Sample/StatsigSamples.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
5C68BE072AF9A6DC006FD9B5 /* ManyGatesSwiftUIViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C68BE062AF9A6DC006FD9B5 /* ManyGatesSwiftUIViewController.swift */; };
5C68BFBA2AFAA68B006FD9B5 /* ExampleDirectoryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C68BFB92AFAA68B006FD9B5 /* ExampleDirectoryViewController.swift */; };
5C8094602ADF17F2001AF600 /* Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C80945F2ADF17F2001AF600 /* Constants.swift */; };
5C9C31A02B17970900FA7212 /* ManyUpdatesViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C9C319F2B17970900FA7212 /* ManyUpdatesViewController.swift */; };
5CAFD04F2ADAEEDD00ACAF79 /* PerfViewControllerObjC.m in Sources */ = {isa = PBXBuildFile; fileRef = 5CAFD04E2ADAEEDD00ACAF79 /* PerfViewControllerObjC.m */; };
5CD93AB02AF953C2009A5898 /* StatsigSamplesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CD93AAF2AF953C2009A5898 /* StatsigSamplesTests.swift */; };
5CDBFC9A2AD4EFE0002E6E60 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CDBFC992AD4EFE0002E6E60 /* AppDelegate.swift */; };
Expand All @@ -37,6 +38,7 @@
5C68BE062AF9A6DC006FD9B5 /* ManyGatesSwiftUIViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ManyGatesSwiftUIViewController.swift; sourceTree = "<group>"; };
5C68BFB92AFAA68B006FD9B5 /* ExampleDirectoryViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExampleDirectoryViewController.swift; sourceTree = "<group>"; };
5C80945F2ADF17F2001AF600 /* Constants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Constants.swift; sourceTree = "<group>"; };
5C9C319F2B17970900FA7212 /* ManyUpdatesViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ManyUpdatesViewController.swift; sourceTree = "<group>"; };
5CAFD04D2ADAEEDD00ACAF79 /* PerfViewControllerObjC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PerfViewControllerObjC.h; sourceTree = "<group>"; };
5CAFD04E2ADAEEDD00ACAF79 /* PerfViewControllerObjC.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PerfViewControllerObjC.m; sourceTree = "<group>"; };
5CD93AAD2AF953C2009A5898 /* StatsigSamplesTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = StatsigSamplesTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
Expand Down Expand Up @@ -83,6 +85,7 @@
5C10DDA82AD4FB60003C4CE1 /* BasicViewControllerObjC.m */,
5CAFD04D2ADAEEDD00ACAF79 /* PerfViewControllerObjC.h */,
5CAFD04E2ADAEEDD00ACAF79 /* PerfViewControllerObjC.m */,
5C9C319F2B17970900FA7212 /* ManyUpdatesViewController.swift */,
5CDBFC9D2AD4EFE0002E6E60 /* BasicViewController.swift */,
5C68BE062AF9A6DC006FD9B5 /* ManyGatesSwiftUIViewController.swift */,
);
Expand Down Expand Up @@ -253,6 +256,7 @@
5C68BE072AF9A6DC006FD9B5 /* ManyGatesSwiftUIViewController.swift in Sources */,
5CAFD04F2ADAEEDD00ACAF79 /* PerfViewControllerObjC.m in Sources */,
5CDBFC9E2AD4EFE0002E6E60 /* BasicViewController.swift in Sources */,
5C9C31A02B17970900FA7212 /* ManyUpdatesViewController.swift in Sources */,
5CDBFC9A2AD4EFE0002E6E60 /* AppDelegate.swift in Sources */,
5C68BFBA2AFAA68B006FD9B5 /* ExampleDirectoryViewController.swift in Sources */,
5C8094602ADF17F2001AF600 /* Constants.swift in Sources */,
Expand Down
10 changes: 5 additions & 5 deletions Sources/Statsig/EventLogger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ class EventLogger {
userDefaults.removeObject(forKey: EventLogger.loggingRequestUserDefaultsKey)

networkService.sendRequestsWithData(failedRequestQueue) { [weak self] failedRequestsData in
guard let failedRequestsData = failedRequestsData, let self = self else { return }
DispatchQueue.main.async {
self.addFailedLogRequest(failedRequestsData)
guard let failedRequestsData = failedRequestsData else { return }
DispatchQueue.main.async { [weak self] in
self?.addFailedLogRequest(failedRequestsData)
}
}
}
Expand Down Expand Up @@ -75,8 +75,8 @@ class EventLogger {
}

func flush() {
logQueue.async {
self.flushInternal(shutdown: false)
logQueue.async { [weak self] in
self?.flushInternal(shutdown: false)
}
}

Expand Down
9 changes: 5 additions & 4 deletions Sources/Statsig/InternalStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -389,11 +389,12 @@ class InternalStore {

func saveValues(_ values: [String: Any], _ cacheKey: UserCacheKey, _ userHash: String?, _ completion: (() -> Void)? = nil) {
storeQueue.async(flags: .barrier) { [weak self] in
guard let self = self else { return }
self.cache.saveValues(values, cacheKey, userHash)
DispatchQueue.global().async {
self.cache.writeToStorage()
self?.cache.saveValues(values, cacheKey, userHash)

DispatchQueue.global().async { [weak self] in
self?.cache.writeToStorage()
}

DispatchQueue.main.async {
completion?()
}
Expand Down
3 changes: 2 additions & 1 deletion Sources/Statsig/NetworkService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -246,10 +246,11 @@ class NetworkService {
completion: @escaping NetworkCompletionHandler,
taskCapture: TaskCaptureHandler
) {
DispatchQueue.main.async {
DispatchQueue.main.async { [weak self] in
let currentAttempt = failedAttempts + 1
marker?.start(attempt: currentAttempt)


let task = URLSession.shared.dataTask(with: request) {
[weak self] responseData, response, error in

Expand Down
2 changes: 1 addition & 1 deletion Sources/Statsig/Statsig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public class Statsig {
}

if options?.enableCacheByFile == true {
DispatchQueue.main.async {
DispatchQueue.main.async {
StatsigUserDefaults.defaults = FileBasedUserDefaults()
_initialize()
}
Expand Down
8 changes: 5 additions & 3 deletions Sources/Statsig/StatsigClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,10 @@ public class StatsigClient {
"evalReason": "\(self.store.cache.reason)"
]

DispatchQueue.main.async {
DebugViewController.show(self.sdkKey, state)
DispatchQueue.main.async { [weak self] in
if let self = self {
DebugViewController.show(self.sdkKey, state)
}
}
}

Expand Down Expand Up @@ -705,7 +707,7 @@ extension StatsigClient {
store.updateUser(currentUser)
logger.user = currentUser

DispatchQueue.main.async { [weak self, completion] in
DispatchQueue.main.async { [weak self] in
self?.fetchValuesFromNetwork { [weak self, completion] error in
guard let self = self else {
return
Expand Down

0 comments on commit 971fd08

Please sign in to comment.