@ SuppressWarnings ( "unchecked" ) public static < V extends View < ? extends VM > , VM extends ViewModel > void createAndInjectViewModel ( final V view , Consumer < ViewModel > newVmConsumer ) { final Class < ? > viewModelType = TypeResolver . resolveRawArgument ( View . class , view . getClass ( ) ) ; if ( viewModelType == ViewModel . class ) { // if no viewModel can be created, we have to check if the user has // tried to inject a ViewModel final List < Field > viewModelFields = ViewLoaderReflectionUtils . getViewModelFields ( view . getClass ( ) ) ; if ( ! viewModelFields . isEmpty ( ) ) { throw new RuntimeException ( "The given view of type <" + view . getClass ( ) + "> has no generic viewModel type declared but tries to inject a viewModel." ) ; } return ; } if ( viewModelType == TypeResolver . Unknown . class ) { return ; } final Optional < Field > fieldOptional = getViewModelField ( view . getClass ( ) , viewModelType ) ; if ( fieldOptional . isPresent ( ) ) { Field field = fieldOptional . get ( ) ; ReflectionUtils . accessMember ( field , ( ) -> { Object existingViewModel = field . get ( view ) ; if ( existingViewModel == null ) { final Object newViewModel = DependencyInjector . getInstance ( ) . getInstanceOf ( viewModelType ) ; field . set ( view , newViewModel ) ; newVmConsumer . accept ( ( ViewModel ) newViewModel ) ; } } , "Can't inject ViewModel of type <" + viewModelType + "> into the view <" + view + ">" ) ; } }
This method is used to create and inject the ViewModel for a given View instance .