简体   繁体   中英

Android MVP Architecture and Realm - How to Avoid Passing Context among the MVP layers?

I have been learning Android MVP for awhile, in most of my Application, I find that it is not so practical to passing the Context Data among the MVP Layer for testability purposes.

However, for some cases, it is required to do so, for example, in order to access Realm database, I would need the Context Data for performing this implementation:

Realm Implementation

 Realm.init(mainContext)

        val config = RealmConfiguration.Builder()
                .name(mainContext.getString(R.string.accountRealm))
                .build()

        realm = Realm.getInstance(config)

Only that I can perform the CRUD functionality of Realm.

Because of that I have to always pass the Context Data from View Layer to Model Layer which I believe which is not so practical.

My Question:

  1. Is there any other way for me to implement the Realm functionality without the need to use the Context Data ? How should I do it in the right way?

  2. Is it okay/acceptable to keep passing Context Data or other similar android specific code among the MVP layer? Like for this Realm case, is it consider as an 'Acceptable Trade-off'?

There two flaws (if I may call so) in the code snippet.

First. Realm.init(mainContext) should be done in onCreate() of Application, just once.

public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    Realm.init(this);
  }
}

Then add MyApplication to your manifest.xml file as below.

<application
  android:name=".MyApplication"
  <!--rest of properties-->
/>

Second. It's usually good idea to read static strings from resources, but not in all case. This case, for example, is an exception.

Create a java class to hold your database name as belowe:

public class AppStatics{
    public final static REALM_DATABASE_NAME = "myrealm.realm";
}

Then simply take database name from this class to set name for Realm database. . You don't have to configure Realm everytime.

public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    Realm.init(this);
    RealmConfiguration.Builder()
            .name(mainContext.getString(R.string.accountRealm))
            .build()
    Realm.setDefaultConfiguration(config);
  }
}

Now you can call instance of Realm by calling Realm realm = Realm.getDefaultInstance(); in your Model (data operations module of MVP)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM