jeudi 23 janvier 2020

Ways to share common data in Android app?

How to share state/data across several Activities and all parts of application?

I have found few ways to achieve this after some research:

  1. Class with data (for example POJO that contains user data) to share must become Singleton and is called like this:
class MyActivity extends Activity {
  ...

@Override
public void onCreate(...){
  super.onCreate();
  // user is initialised somewhere else  
  final User user = User.instance();
  final String username = user.name();
}
  1. Class with data becomes static member of Application class
class App extends Application { 
  private static User sUser;

  public static User currentUser() {
    return sUser;
  }

//usage:
...
final User user= App.currentUser();
...
  1. Class with data becomes field of Application class
class App extends Application { 
  private User sUser;

  public User currentUser() {
    return sUser;
  }

//usage:
...
final User user= ((App)getApplicationContext()).currentUser();
...
  1. Class with data is injected using some DI framework (Dagger, Koin, etc.)
  2. I have created apps using React Native and Redux architecture, so I think Redux can be used in Android somehow too?

Which way do you prefer? What are the pros and cons of each way above?
Thank you for your feedback!

Aucun commentaire:

Enregistrer un commentaire