Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Room without ViewModel

I just started using android room. Only problem is, It takes several layers for db interaction. Table Class -> Dao Interface -> Database Repo -> ViewModels

And in each layer, code repetition is there.

As if I directly call queries from Repo, without viewModels, it will not allow. Because call without viewModel observer becomes synchronous, which blocks main thread.

Either there must be standard way to call repo asynchronously, or some hacks. May be we can use some Async generic class, which lets you pass queries and return result to main thread.

Possible hack. Don't knwo if it is correct way.

    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            List<User> users = apiService.getAllUsers();
            if(users.size()>0)
            {
                System.out.println("Total users:"+users.size());
                System.out.println("Email:"+users.get(0).getEmail());
            }
        }
    });
like image 257
Mukarram Ali Avatar asked Oct 18 '25 04:10

Mukarram Ali


1 Answers

You can use an AsyncTask for this without the need for ViewModels.

AsyncTask.execute {
            val entity = daoInterface.queryFunction()
            ...
        }
like image 93
Stephan Avatar answered Oct 19 '25 20:10

Stephan