5

我复制了一个带有 Android 架构组件、Retrofit、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>,但我不再拥有代码。我也尝试过搜索,但没有得到好的结果。也许我没有搜索合适的术语。我很感激任何指导。

4

1 回答 1

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);
}
于 2018-08-27T06:44:25.090 回答