Repository module implementation with Context

11.1k views Asked by At

I would like to implement Repository module to handle data operations. I have JSON file in row directory and want create concrete Repository implementation to get data from file. I'm not sure if I can use Context as attribute in the constructor or method of Repository.

e.g.

public class UserRepository {

    UserRepository() {}

    public List<User> loadUserFromFile(Context contex) {
        return parseResource(context, R.raw.users);
    }
}
2

There are 2 answers

1
Hannoun Yassir On

I don't see any harm in passing the context as an attribute. If you dislike the idea then you can retrieve the context via a convenient method : Static way to get 'Context' on Android?

2
Chintan Soni On

IMHO, you should use DI (Dependency Injection) like Dagger2, to provide you Context something like,

AppModule.class

@Module
public class AppModule {

    private Context context;

    public AppModule(@NonNull Context context) {
        this.context = context;
    }

    @Singleton
    @Provides
    @NonNull
    public Context provideContext(){
        return context;
    }

}

MyApplication.class

public class MyApplication extends Application {

    private static AppComponent appComponent;

    public static AppComponent getAppComponent() {
        return appComponent;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent = buildComponent();
    }

    public AppComponent buildComponent(){
        return DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .build();
    }
}

UserRepository.class

@Singleton
public class UserRepository {

    UserRepository() {}

    @Inject
    public List<User> loadUserFromFile(Context contex) {
        return parseResource(context, R.raw.users);
    }
}

Happy Coding..!!