Jasmin Fajkic
07/23/2022, 6:39 PM@EntryPoint
@InstallIn(ActivityComponent::class)
interface ViewModelFactoryProvider {
fun communityFeedViewModelFactory(): CommunityFeedViewModel.Factory
fun postTileViewModelFactory(): PostTileViewModel.Factory
fun reactionViewModelFactory(): ReactionsViewModel.Factory
fun commentViewModelFactory(): CommentViewModel.Factory
}
Here is for example how i use it in ReactionsViewModel
class ReactionsViewModel
@AssistedInject
constructor(
@Assisted private var reactions: PostReactions,
@Assisted private var postId: String,
private var reactionsRepository: ReactionsRepository,
) : ViewModel() {
@AssistedFactory
interface Factory {
fun create(
@Assisted reactions: PostReactions,
@Assisted postId: String,
): ReactionsViewModel
}
@Suppress("UNCHECKED_CAST")
companion object {
fun provideFactory(
assistedFactory: Factory,
reactions: PostReactions,
postId: String
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return assistedFactory.create(reactions, postId) as T
}
}
}
}
@Composable
fun reactionsViewModel(
reactions: PostReactions,
id: String
): ReactionsViewModel {
val factory = EntryPointAccessors.fromActivity(
LocalContext.current as Activity,
ViewModelFactoryProvider::class.java
).reactionViewModelFactory()
return viewModel(
factory = ReactionsViewModel.provideFactory(
factory,
reactions,
postId = id,
), key = id
)
}
And here is how I provide reactions respository:
@Module
@InstallIn(ActivityComponent::class)
object ReactionsModule {
@Provides
fun provideReactionApi(retrofit: Retrofit):
ReactionsApi = retrofit.create(ReactionsApi::class.java)
@Provides
fun providesRRepository(ReactionsApi: ReactionsApi):
ReactionsRepository =
ReactionsRepositoryImpl(ReactionsApi)
}
Problem here is that I need to use ActivityComponent in module where I provide repository. If i try to access this reactions repository in any other viewmodel it crash because it needs to be ViewModelComponent. Is there any clever solution how to fix it?