How to instantiate the database and my repositories, Guide to app architecture

Viewed 186

I am making a fairly simple application that consists of listing some users, and if it is given in the detail, another activity opens showing a list of their publications, this with data from the well-known JsonPlaceHolder API.

The point is that I am making the app with the best possible architecture, following the documentation and basically the structure below.

enter image description here

the problem is that the app feels very slow, maybe someone helps me identify the problem, thanks

this way I install my DB with Room and the repositories I use

    class App: Application(){
    
        private val applicationScope = CoroutineScope(SupervisorJob())
    
        // Using by lazy so the database and the repository are only created when they're needed
        // rather than when the application starts
        private val database by lazy { UserRoomDatabase.getDatabase(this, applicationScope) }
        val userRepository by lazy { UserRepository(database.userDao()) }
        val postRepository by lazy { PostRepository(database.postDao()) }
    
    }

so I initialize view models in my activities

    private val postViewModel: PostViewModel by viewModels {
            PostViewModelFactory((application as App).postRepository)
        }

I think this is the most important thing to show and maybe here's what I'm doing wrong that makes my app a bit slow. If you need something else, ask me.

I was reading docs and according to them I can use Dagger to inject this, but the truth with this as I have it, I do not see the problem.

2 Answers

I have not slept in two whole days but I am very happy to say that I have finally been able to make an app with a perfect architecture: D and understanding everything, I feel that I have taken a great step in mobile development. I have found the solution using dagger hilt (How to create and use a Room Database in Kotlin [Dagger-Hilt]), I will leave the link of an answer that helped me a lot.

Here you can find basic information on dependency injection for those who do not know anything yet Dependency injection in Android

My problem was basically one of dependencies, and with dagger hilt I solved this, besides that now it will be much easier for me to do tests.

Thanks also to @Muhammad Asad for you help.

Use siglent pattern to create the repositories object using Daggar hilt and make sure that resources of the app in Batch drawable importer if you using big size resource then view take some time to rendering. Mostly application crash with memory leak issue.

Related