\$\begingroup\$
\$\endgroup\$
1
I implemented a class for relationships with the user (deletion, name change, check for existence), I created this class to remove extra logic from the activity class. Could you talk about how my code can be improved?
class UserActionManager @Inject constructor(private val repository : BaseAppRepository,
private val sharedPreferences : JsonSharedPreferences) {
fun editUserName(user: User,newUserName: String) {
Completable.fromAction {
val userObjective:Objective? = sharedPreferences.loadObject(GlobalConstants.OBJECTIVE_SAVE_KEY + user.userName,Objective::class.java)
val userProfile:Profile? = sharedPreferences.loadObject(GlobalConstants.PROFILE_SAVE_KEY + user.userName,Profile::class.java)
sharedPreferences.saveObject<Objective>(GlobalConstants.OBJECTIVE_SAVE_KEY + newUserName, userObjective)
sharedPreferences.saveObject<Profile>(GlobalConstants.PROFILE_SAVE_KEY + newUserName, userProfile)
repository.updateUserName(user.userName, newUserName)
user.userName = newUserName
repository.updateUser(user)
}.subscribeOn(Schedulers.io()).subscribe()
}
fun deleteUser(user: User) {
Completable.fromAction { repository.deleteUser(user) }.subscribeOn(Schedulers.io()).subscribe()
sharedPreferences.saveObject<Objective>(GlobalConstants.OBJECTIVE_SAVE_KEY + user.userName, null)
sharedPreferences.saveObject<Profile>(GlobalConstants.PROFILE_SAVE_KEY + user.userName, null)
}
fun isEmptyUser(userName: String): Single<Boolean> {
return repository.getUserByUserName(userName)
.subscribeOn(Schedulers.io())
.isEmpty
}
}
DestroyerDestroyer
asked Apr 21, 2020 at 9:57
-
1\$\begingroup\$ Search for kotlin - coroutines. This is the Kotlin-version for RX with a lot of syntactic sugar maybe medium.com/@daptronic/… can help \$\endgroup\$tieskedh– tieskedh2020年04月22日 11:14:31 +00:00Commented Apr 22, 2020 at 11:14
1 Answer 1
\$\begingroup\$
\$\endgroup\$
- Extract your preferences code into extra class or create extension functions to get those objects. Ex.
sharedPreferences.loadObject(GlobalConstants.OBJECTIVE_SAVE_KEY + user.userName,Objective::class.java)
should have it's own method. Ex.loadUserByName
. - You are using kotlin, use it's strengths like non-nullables by default. Does
repository.updateUserName()
really accept nullables? That seems wrong. I'd use it for example with elvis operatorloadUserByName(user.username) ?: error("username not found")
default