gpt4 book ai didi

android - 如何让这个 ViewModelFactory 更灵活并接受不同种类的 ViewModel 类?

转载 作者:行者123 更新时间:2023-12-03 17:32:03 24 4
gpt4 key购买 nike

我复制了一个带有 Android 架构组件、Retrofit、Dagger 和数据绑定(bind)的 MVVM 示例。我将此代码用作我的应用程序的起点,以便开始在 Android 应用程序开发中使用更好的架构。但是,请使用以下代码:

interface ViewModelInjector {
/**
* Injects required dependencies into the specified PostListViewModel.
* @param postListViewModel PostListViewModel in which to inject the dependencies
*/
fun inject(postListViewModel: PostListViewModel)

@Component.Builder
interface Builder {
fun build(): ViewModelInjector
fun networkModule(networkModule: NetworkModule): Builder
}
}


class ViewModelFactory(private val activity: AppCompatActivity) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(PostListViewModel::class.java)) {
val db = Room.databaseBuilder(
activity.applicationContext,
AppDatabase::class.java,
"posts"
).build()

@Suppress("UNCHECKED_CAST")
return PostListViewModel(db.postDao()) as T
}

throw IllegalArgumentException("Unknown ViewModel class")
}
}


abstract class BaseViewModel : ViewModel() {
private val injector: ViewModelInjector = DaggerViewModelInjector
.builder()
.networkModule(NetworkModule)
.build()

init {
inject()
}

private fun inject() {
when (this) {
is PostListViewModel -> injector.inject(this)
}
}
}

主要问题是它被 PostListViewModel 卡住了。 .我想以动态的方式制作它,接受任何类型的 [Name]ViewModel类(class)。我确实尝试了一些使用 Class<T> 的方法,但我不再有代码。我也尝试过搜索,但没有得到好的结果。也许我没有搜索合适的术语。我很感激任何指导。

最佳答案

最近我遇到了同样的问题,我发现了 generic ViewModelFactory ,它是java但是..

@Singleton
public class ViewModelFactory implements ViewModelProvider.Factory {
private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;

@Inject
public ViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
this.creators = creators;
}

@NonNull
@SuppressWarnings("unchecked")
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
Provider<? extends ViewModel> creator = creators.get(modelClass);
if (creator == null) {
for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
if (modelClass.isAssignableFrom(entry.getKey())) {
creator = entry.getValue();
break;
}
}
}
if (creator == null) {
throw new IllegalArgumentException("unknown model class " + modelClass);
}
try {
return (T) creator.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

我放了引用链接,但我还找不到它..

编辑:
@Singleton
@Component(modules={ActivityModule.class, FragmentModule.class, AppModule.class})
public interface AppComponents {

@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
AppComponents build();
}

void inject(Weather weatherApp);
}

现在,您对以上类(class)感兴趣的应该是 AppModule.class
@Module(includes = {UserModelModule.class /* other model modules */})
public class AppModule {

// --- DATABASE INJECTION ---

@Provides
@Singleton
YourDatabase provideDatabase(Application application) {
return Room.databaseBuilder(application,
YourDatabase.class, "YourDatabase.db")
//.allowMainThreadQueries() // do NOT DO THIS IN REAL APPLICATIONs
.fallbackToDestructiveMigration()
.build();
}

@Provides
@Singleton
UserDao provideUserDao(YourDatabase database) { return database.userDao(); }
.
.
// other Daos that you will have (the above is an example from [https://developer.android.com/jetpack/docs/guide]

最后,我想你会想看看 ModelModule 类的样子
@Module
public abstract class UserModelModule {

@Binds
@IntoMap
@ViewModelKey(UserViewModel.class)
abstract ViewModel bindUserProfileViewModel(UserViewModel repoViewModel);

@Binds
abstract ViewModelProvider.Factory bindViewModelFactory(ViewModelFactory factory);
}

关于android - 如何让这个 ViewModelFactory 更灵活并接受不同种类的 ViewModel 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52033403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com