Search code examples
androidkotlinsingletonviewmodel

Data Transfer betwen activities. Kotlin Singleton with Parameters? Other questions


A list/set of 5-200 objects (depending on App user) with five 40 character String variables needs to be common between Activities.

ViewModels are good for data transfer between Fragments but seemingly it is not that good for data transfer between Activities as the lifecycle of ViewModel is scoped to a single activity's lifecycle.

Question 1: Is is possible to make the whole application -instead of single Activity- ViewModelStoreOwner ? If yes how? Would you suggest a ViewModelSingleton?

Question 2: How about using an ordinary singleton instead? What are pros and cons compared to ViewModel and ViewModelSingleton? Is there a chance a singleton be sent to garbage collector and data get lost?

Question 3: object in Kotlin defines a thread safe, lazily instantiated singleton which is awesome, but it is not possible to pass in parameters directly. There are various methods to pass in parameters. What method do you suggest and why?

Question 4: Using sharedPreferences to pass data is also possible but seems to be slow. Any fast, robust and flexible way that you would suggest other than the methods mentioned so far?

Thank you.


Solution

  • If your data is a reasonably small size like yours, used throughout the application, singleton makes sense to me. But not a "ViewModel" singleton. Your model class should be the singleton, not the ViewModel, which contains the logic of working with the model data and should be scoped to an Activity (and a new instance created for each Activity).

    Your singleton model can be a traditional singleton or an object with an initialization function you have to call. That's just preference. Only your ViewModel that works with the singleton has to access it, so the boilerplate usage will probably be about the same either way.

    Sometimes, singletons in Android need a context, like if you are saving to files or a database. In that case, the Application should be used for the Context, so you can't accidentally pass an Activity across the View/ViewModel barrier and leak it. You can use AndroidViewModel so your ViewModel will have an Application instance it can use to retrieve the singleton.

    SharedPreferences will also work, and is not typically slow because it keeps data in memory and saves it to file in the background. But then you're doing unnecessary file writing.