@@ -87,16 +87,67 @@ dependencies {
87
87
88
88
## Basic Usage
89
89
90
+ First, provide SafeBox as a singleton:
91
+
92
+ ``` kotlin
93
+ @Singleton
94
+ @Provides
95
+ fun provideEncryptedSharedPreferences (@ApplicationContext context : Context ): SharedPreferences =
96
+ SafeBox .create(context, PREF_FILE_NAME ) // Replacing EncryptedSharedPreferences
97
+ ```
98
+
99
+ Or use the built-in singleton helper:
100
+
90
101
``` kotlin
91
- val safeBox = SafeBox .create(context, fileName = " secure-prefs" )
102
+ SafeBoxProvider .init (context, PREF_FILE_NAME )
103
+ val prefs = SafeBoxProvider .get()
104
+ ```
92
105
93
- safeBox.edit()
106
+ Then use it like any ` SharedPreferences ` :
107
+
108
+ ``` kotlin
109
+ prefs.edit()
94
110
.putInt(" userId" , 123 )
95
111
.putString(" name" , " Luna Moonlight" )
96
112
.apply ()
97
113
98
- val userId = safeBox.getInt(" userId" , - 1 )
99
- val email = safeBox.getString(" email" , null )
114
+ val userId = prefs.getInt(" userId" , - 1 )
115
+ val email = prefs.getString(" email" , null )
116
+ ```
117
+
118
+ ### Anti-Patterns
119
+
120
+ #### ❌ Do NOT create multiple SafeBox instances with the same file name
121
+
122
+ ``` kotlin
123
+ class HomeViewModel @Inject constructor() : ViewModel() {
124
+
125
+ private val safeBox = SafeBox .create(context, PREF_FILE_NAME ) // ❌ New instance per ViewModel
126
+ }
127
+ ```
128
+
129
+ This may cause FileChannel conflicts, memory leaks, or stale reads across instances.
130
+
131
+ ---
132
+
133
+ #### ⚠️ Avoid scoping SafeBox to short-lived components
134
+
135
+ ``` kotlin
136
+ @Module
137
+ @InstallIn(ViewModelComponent ::class ) // ⚠️ New instance per ViewModel
138
+ object SomeModule {
139
+
140
+ @Provides
141
+ fun provideSafeBox (@ApplicationContext context : Context ): SafeBox =
142
+ SafeBox .create(context, PREF_FILE_NAME )
143
+ }
144
+
145
+ class HomeViewModel @Inject constructor(private val safeBox : SafeBox ) : ViewModel() {
146
+
147
+ override fun onCleared () {
148
+ safeBox.close() // Technically safe, but why re-create SafeBox for every ViewModel?
149
+ }
150
+ }
100
151
```
101
152
102
153
## Migrating from EncryptedSharedPreferences
0 commit comments