Should we use Contex in view model of Android?
Arun Aditya
Android Engineer @ Mercedes-Benz | Specializing in Android, Kotlin, and Java | MVVM & Clean Code Advocate | Building efficient mobile apps
It is generally not recommended to use context to a view model constructor in Android. This is because view models are supposed to be agnostic of the UI and should not have any direct dependencies on Android framework classes.
Passing context to a view model can lead to memory leaks and make it difficult to test the view model in isolation. It can also make it more difficult to maintain the code, as the view model will become more tightly coupled to the UI.
Instead of passing context to the view model constructor, you should inject any dependencies that the view model needs through dependency injection. This will make the view model more testable and maintainable.
If you need to access context in a view model, you should use one of the following methods:
Example 1 : How to inject context into a view model using Dagger
领英推荐
@Module
object AppModule {
@Provides
fun provideContext(application: Application): Context = application.applicationContext
}
@HiltViewModel
class MyViewModel @Inject constructor(private val context: Context) {
// ...
}
Example 2: How to get context from the view model’s owner
class MyFragment : Fragment() {
private val viewModel: MyViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// ...
viewModel.getSomeData(context)
// ...
}
}
Example 3: How to use a LiveData object to observe changes to context:
class MyViewModel : ViewModel() {
private val contextLiveData = MutableLiveData<Context>()
init {
contextLiveData.observeForever { context ->
// Do something with context
}
}
fun setContext(context: Context) {
contextLiveData.value = context
}
// ...
}
You can use these methods to access context in a view model without making it dependent on context. This is a good practice because it makes your view models more reusable, testable, and memory-efficient.
refrence :
2CS student at ESTIN | Android Full-Stack Developer
3 个月are you sure that it works with dependancy injection ? because i still get this warning "This field leaks a context object"