Search code examples
androidandroid-studiokotlinandroid-mvvm

Having context as primary constructor parameter inside a repository is good or bad


I have a repository called LocationRepository the code of LocationRepository is

class LocationRepository(
       private val context: Context
       private val api: AppApi, 
       private val db:AppDatabase
) : SafeApiRequest() {
}

here you can see that I am passing a context inside through the primary constructor need for that is I have to convert a bitmap to base64 from its Uri you can see the suspended fun below

suspend fun submitLocation(location: Location,employee: Employee) : LocationUpdateResponse{
}

you can see here I am passing location which contains the Uri of the image I have to convert the Uri to base64 before API call, is this best practice or bad?


Solution

  • It's neither a best practice nor bad. Having context there is necessary some times especially when you need it for accessing your database, your shared preferences or getting some resources.

    If you need the context to live in your repository, you need to be sure you are using the application context. If you are using an activity's context, then you would leak your activities when the activities go away but the repository is not.

    Both Activity and Application context are very similar as to what they are providing. The difference is that Activity context is tied to the activity's lifecycle where the application context is tied to the application lifecycle.

    Now, since the application will live as long as your repository then it's fine to use application context in your repository.