2
\$\begingroup\$

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
    }
}
\$\endgroup\$
1
  • 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
    Apr 22, 2020 at 11:14

1 Answer 1

2
\$\begingroup\$
  • 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 operator loadUserByName(user.username) ?: error("username not found")
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.