3

I have a question regarding objects in kotlin, to which I couldn't find a satisfying answer so far. It's basically the following scenario: I've got some user data, that I want to make available through the entire app, without having to pass it through activities.

To achieve this, I created an object with two properties that are instantiated with the user's data in the startup activity. Is this a safe way to store and make the user's data available for all activities or will it get lost on the way?

Example:

object CurrentUserManager {
    lateinit var userId: String,
    lateinit var userName: String
    }

LoginActivity {
    ...
    onCreate(...){
        val user = ApiCall.Login();
        CurrentUserManager.userId = user.id
        CurrentUserManager.userName = user.name
    }
}

MainActivity {
    ...
    onCreate(...){
        Toast.makeText(this, "Hello ${CurrentUserManager.userName} with ID: ${CurrentUserManager.userId}", Toast.LENGTH_SHORT).show()
    }
}

Is this unsafe/bad practice and if so why and which pattern should I use to achieve the expected outcome?

Thanks, lionthefox

Prince Dholakiya
  • 3,255
  • 27
  • 43
lionthefox
  • 369
  • 1
  • 2
  • 16

2 Answers2

3

Short answer: it's safe as long as your Android process does not end.

Long answer: this boils down to the discussion about lifetime of singletons and static variables in Java. There have already been some answers to this very question, so I won't re-iterate those here:

TheOperator
  • 5,936
  • 29
  • 42
-1

use intent put extras or maintain a static Object

  • " I've got some user data, that i want to make available through the entire app, without having to pass it through activities." using intent.putExtra() is exactly what i want to avoid – lionthefox May 08 '19 at 10:38
  • and I'm already using the static kotlin object and wanna know if it is safe this way, so your answer doesn't really help me here – lionthefox May 08 '19 at 10:45
  • use static is a simple and efficient way to handle this problem,but the safety depency on yourself. I use this method too.if you want other way better,like you say i can not help you. – Tobiah Shaw May 08 '19 at 11:06
  • Please read carefully... This is Kotlin not Java. There is no static keyword. The equivalent to java's statics are companion objects / objects – lionthefox May 08 '19 at 11:21