ViewModelProvider { @NonNull @MainThread public <T extends ViewModel> T get(@NonNull Class<T> modelClass) { String canonicalName = modelClass.getCanonicalName(); if (canonicalName == null) { throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels"); } return get(DEFAULT_KEY + ":" + canonicalName, modelClass); } ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory);  ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory); @NonNull @MainThread T get(@NonNull Class<T> modelClass); @SuppressWarnings("unchecked") @NonNull @MainThread T get(@NonNull String key, @NonNull Class<T> modelClass);  }
@Test public void twoViewModelsWithSameKey() throws Throwable { String key = "the_key"; ViewModel1 vm1 = mViewModelProvider.get(key, ViewModel1.class); assertThat(vm1.mCleared, is(false)); ViewModel2 vw2 = mViewModelProvider.get(key, ViewModel2.class); assertThat(vw2, notNullValue()); assertThat(vm1.mCleared, is(true)); }
@Test public void localViewModel() throws Throwable { class VM extends ViewModel1 { } try { mViewModelProvider.get(VM.class); Assert.fail(); } catch (IllegalArgumentException ignored) { } }
@Test public void twoViewModels() { ViewModel1 model1 = mViewModelProvider.get(ViewModel1.class); ViewModel2 model2 = mViewModelProvider.get(ViewModel2.class); assertThat(mViewModelProvider.get(ViewModel1.class), is(model1)); assertThat(mViewModelProvider.get(ViewModel2.class), is(model2)); }
@Test public void testOwnedBy() { final ViewModelStore store = new ViewModelStore(); ViewModelStoreOwner owner = new ViewModelStoreOwner() { @NonNull @Override public ViewModelStore getViewModelStore() { return store; } }; ViewModelProvider provider = new ViewModelProvider(owner, new NewInstanceFactory()); ViewModel1 viewModel = provider.get(ViewModel1.class); assertThat(viewModel, is(provider.get(ViewModel1.class))); }
@Test public void testKeyedFactory() { final ViewModelStore store = new ViewModelStore(); ViewModelStoreOwner owner = new ViewModelStoreOwner() { @NonNull @Override public ViewModelStore getViewModelStore() { return store; } }; ViewModelProvider.KeyedFactory keyed = new ViewModelProvider.KeyedFactory() { @NonNull @Override public <T extends ViewModel> T create(@NonNull String key, @NonNull Class<T> modelClass) { assertThat(key, is("customkey")); return (T) new ViewModel1(); } }; ViewModelProvider provider = new ViewModelProvider(owner, keyed); provider.get("customkey", ViewModel1.class); }