2

I am using MVVM for my application. I want to get context in my viewmodel or in repository in better way.

Let's pretend I have UserRepository() class

public class UserRepository {
    UserDao userDao;
    Executor executor;

    public UserRepository() {
        this.userDao = AppDatabase.getAppDatabase(MApplication.context).userDao();
        executor = Executors.newSingleThreadExecutor();
    }

    public void clearUserCached() {
        executor.execute(() -> {
            userDao.deleteAll();
        });
    }

    public void loginUser(String email, String password) {

        getAPIService().login(new LoginRequest(email, password))
            .compose(RxUtils.applySchedulers())
            .subscribe(
                (LoginResponse response) -> {
                    executor.execute(() -> {
                        userDao.insert(response.getUser());
                    });
                },
                (Throwable e) -> {
                    e.printStackTrace();
                }
            );
    }

    public LiveData<User> getUser() {
        return userDao.getUser();
    }
}

I know using MApplication.context is not a good approach. This is memory leak.

What's another way to to get context ?

Note: I am not using Dagger2

pmb
  • 2,327
  • 3
  • 30
  • 47

1 Answers1

-1

In your constructor, add a Context parameter then, when you want to use this class, pass the context to it and use that context wherever in the viewModel. Just like this:

 Context context;
 public UserRepository(Context context) {
    this.userDao = AppDatabase.getAppDatabase(MApplication.context).userDao();
    executor = Executors.newSingleThreadExecutor();
    context.this = context;
}

and assume that your main activity is using UserRepository class:

UserRepository userRepository = new UserRepository(MatinActivity.this);

then, you have context in your UserRepository class and you can use it.

Matin Gdz
  • 217
  • 2
  • 13
  • I think the TS is trying to pass the context to the viewmodel and not in the activity – Cyd Jan 20 '20 at 05:55