Home > Software design >  MVVM: Set a getDrawable from a ViewModel
MVVM: Set a getDrawable from a ViewModel

Time:06-30

I'm moving all my app's logic from the fragment to the ViewModel and cannot move those methods that set drawables. Example:

marker.icon = ContextCompat.getDrawable(requireContext(), R.drawable.waypoints_sq_blank)

The reason being that the context is not reachable from a ViewModel. Any way I can get this to work?

CodePudding user response:

The best practice for your queestion is using hilt dependency injection and injecting a custom class to your view model constructor

you can create a class to use it in all view models like this:

class AppResourceProvider(private val context: Context) {
    fun getString(id: Int): String {
        return context.getString(id)
    }

    fun getDrawable(@DrawableRes id: Int): Drawable{
        return ContextCompat.getDrawable(context, id)
    }
}

Then you need to inject this class to your appModule:

@Module
@InstallIn(SingletonComponent::class)
class AppModule {

    @Provides
    @Singleton
    fun provideAppResourceProvider(@ApplicationContext context: Context): AppResourceProvider{
        return AppResourceProvider(context)
    }
 }

finally you can use it in your all viewModels like this:

class SampleViewModel @Inject constructor(
    private val resourceProvider: AppResourceProvider
){
    fun whereYouNeed(){
        marker.icon = resourceProvider.getDrawable(R.drawable.waypoints_sq_blank)
    }
}
  • Related