如何使此ViewModelFactory更灵活并接受不同种类的ViewModel类?

时间:2018-08-27 06:07:29

标签: android android-viewmodel android-mvvm

我复制了带有Android体系结构组件,翻新,Dagger和数据绑定的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<T>尝试了一些方法,但是我不再有代码了。我也尝试搜索,但未取得良好结果。也许我没有搜索适当的术语。感谢您的指导。

1 个答案:

答案 0 :(得分:0)

最近我遇到了同样的问题,我发现了一个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);
}

现在,您对以上课程感兴趣的是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);
}