Setter() {} seems to update property with delay


#1

Somehow, on my UserManager singleton, if I and only if I set a setter() {} block on the .accessToken property, there is a delay when it is actually set with the new value.


#2

Sounds like you are doing something else wrong. Can you give us a few more specific information about what you are doing. Also what system are you on? JVM, android, native or js?


#3

I am on the android system.

The context is

class UserManager () {
   val accessToken  = INITIAL_VALUE
      setter (value) {
          updateSharedPreferences(value)
      }

     // etc.

     fun updateSharedPreferences(newToken: String) {
       
     }

     companion objection () {
          fun getInstance(context: Context) : UserManager { 
              // creates singleton instance of class by injecting with context if not already extant
          }
     }
}

And in one activity when I call

      UserManager.getInstance(context).accessToken = newAccessToken

I then proceed to go to another activity, which has a Network Manager which references

      UserManager.getInstance(context).accessToken

for the request headers of a retrofit network instance. When a network request is made in the activity which is loaded synchronously after the former statement, UserManager.getInstance(context).accessToken still has the old value. We have deduced that it updating sharedPreferences within the context of the setter which causes the new value to seem to be dispatched on the same main thread as opposed to being pushed immediately on the execution stack of the main thread. That seems to be the only explanation since when we change the former to:

       UserManager.getInstance(context).accessToken = NEW_ACCESS_TOKEN
       UserManager.getInstance(context).updateSharedPreferences(NEW_ACCESS_TOKEN)

then everything executes synchronously and our retrofit instance references the correct value.


#4

Your set is not actually setting the value of the property. So it is always returning INITIAL_VALUE.

var accessToken  = INITIAL_VALUE
    set(value) {
        field = value // this is missing
        updateSharedPreferences(value)
    }