Skip to content

Commit d8bf7f0

Browse files
committed
feat: rely on StoreManager instead of custom tracker
1 parent c648436 commit d8bf7f0

2 files changed

Lines changed: 24 additions & 18 deletions

File tree

packages/brownie/android/src/main/java/com/callstack/brownie/BrownieStoreRegistration.kt

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
package com.callstack.brownie
22

3-
import java.util.concurrent.ConcurrentHashMap
4-
import java.util.concurrent.atomic.AtomicBoolean
5-
63
/**
74
* Registers a new [Store] instance from this definition and the provided initial state.
85
*/
@@ -27,26 +24,17 @@ inline fun <reified State : Any> registerStore(
2724
initialState: State,
2825
): Store<State> = registerStore(storeName, initialState, State::class.java)
2926

30-
private object BrownieStoreRegistrationTracker {
31-
private val didRegisterByKey = ConcurrentHashMap<String, AtomicBoolean>()
32-
33-
/**
34-
* Returns true only for the first registration attempt of a given store key.
35-
*/
36-
fun markRegistered(key: String): Boolean {
37-
val registrationFlag = didRegisterByKey.getOrPut(key) { AtomicBoolean(false) }
38-
return registrationFlag.compareAndSet(false, true)
39-
}
40-
}
41-
4227
/**
4328
* Registers once per store name and returns null when the store was already registered.
29+
*
30+
* Idempotency is based on whether a store with this [storeName] currently exists
31+
* in [StoreManager], so clearing or removing a store allows registration again
32+
* within the same process.
4433
*/
4534
fun <State> BrownieStoreDefinition<State>.registerIfNeeded(initialState: () -> State): Store<State>? {
46-
if (!BrownieStoreRegistrationTracker.markRegistered(storeName)) {
47-
return null
35+
return StoreManager.shared.registerIfAbsent(storeName) {
36+
register(initialState())
4837
}
49-
return register(initialState())
5038
}
5139

5240
/**

packages/brownie/android/src/main/java/com/callstack/brownie/StoreManager.kt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,24 @@ class StoreManager private constructor() {
2626
}
2727
}
2828

29+
/**
30+
* Registers a new store only when [key] is currently absent.
31+
*
32+
* Returns the created store when registration succeeds, otherwise `null`.
33+
* The check and registration are atomic under [lock].
34+
*/
35+
fun <State> registerIfAbsent(key: String, createStore: () -> Store<State>): Store<State>? {
36+
return lock.withLock {
37+
if (stores.containsKey(key)) {
38+
return@withLock null
39+
}
40+
41+
val store = createStore()
42+
stores[key] = store
43+
store
44+
}
45+
}
46+
2947
/**
3048
* Retrieves a typed store by key when the runtime state type matches [clazz].
3149
*/

0 commit comments

Comments
 (0)