使用Dagger 2的ViewModelProviders,无法掌握概念

时间:2018-06-04 04:04:01

标签: android retrofit dagger-2 android-architecture-components android-viewmodel

我有像这样的改装服务

public interface BrandsService {
    @GET("listBrand")
    Call<List<Brand>> getBrands();
}

然后我有一个Repository来从这样的api获取数据

public class BrandsRepository {
    public static final String TAG = "BrandsRepository";
    MutableLiveData<List<Brand>> mutableLiveData;
    Retrofit retrofit;

    @Inject
    public BrandsRepository(Retrofit retrofit) {
        this.retrofit = retrofit;
    }

    public LiveData<List<Brand>> getListOfBrands() {
//       Retrofit retrofit = ApiManager.getAdapter();
        final BrandsService brandsService = retrofit.create(BrandsService.class);
        Log.d(TAG, "getListOfBrands: 00000000000 "+retrofit);

        mutableLiveData = new MutableLiveData<>();

        Call<List<Brand>> retrofitCall = brandsService.getBrands();
        retrofitCall.enqueue(new Callback<List<Brand>>() {
            @Override
            public void onResponse(Call<List<Brand>> call, Response<List<Brand>> response) {
                mutableLiveData.setValue(response.body());
            }

            @Override
            public void onFailure(Call<List<Brand>> call, Throwable t) {
                t.printStackTrace();
            }
        });
        return mutableLiveData;

    }
}

我通过注入像这样的Retrofit来使用Dagger2的构造函数注入。 然后我有一个像这样的ViewModel

public class BrandsViewModel extends ViewModel{
    BrandsRepository brandsRepository;
    LiveData<List<Brand>> brandsLiveData;
    @Inject
    public BrandsViewModel(BrandsRepository brandsRepository) {
        this.brandsRepository = brandsRepository;
    }

    public void callService(){
       brandsLiveData = brandsRepository.getListOfBrands();
    }

    public LiveData<List<Brand>> getBrandsLiveData() {
        return brandsLiveData;
    }


}

要在BrandsRepository中注入Retrofit,我必须像这样注入BrandsRepository。 然后我有像这样的MainActivity

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    @Inject
    BrandsViewModel brandsViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ((MainApplication)getApplication()).getNetComponent().inject(this);

//        BrandsViewModel brandsViewModel = ViewModelProviders.of(this).get(BrandsViewModel.class);
        brandsViewModel.callService();

        LiveData<List<Brand>> brandsLiveData = brandsViewModel.getBrandsLiveData();
        brandsLiveData.observe(this, new Observer<List<Brand>>() {
            @Override
            public void onChanged(@Nullable List<Brand> brands) {
                Log.d(TAG, "onCreate: "+brands.get(0).getName());
            }
        });


    }
}

使用Dagger2而不是ViewModelProviders注入BrandsViewModel。这工作正常,但当我尝试通过取消注释使用ViewModelProviders时,dagger给了我很明显的错误。获取ViewModel的正确方法是使用ViewModelProviders,但是如何在注入这样的改进时完成此操作。

2 个答案:

答案 0 :(得分:7)

答案可能比Mumi的方法更简单,即您在组件上公开ViewModel:

@Singleton
@Component(modules={...})
public interface SingletonComponent {
    BrandsViewModel brandsViewModel();
}

现在,您可以在ViewModelFactory中的组件上访问此方法:

// @Inject
BrandsViewModel brandsViewModel;

...
brandsViewModel = ViewModelProviders.of(this, new ViewModelProvider.Factory() {
    @Override
    public <T extends ViewModel> create(Class<T> modelClazz) {
        if(modelClazz == BrandsViewModel.class) {
            return singletonComponent.brandsViewModel();
        }
        throw new IllegalArgumentException("Unexpected class: [" + modelClazz + "]");
    }).get(BrandsViewModel.class);

所有这一切都可以通过Kotlin进行简化和隐藏:

inline fun <reified T: ViewModel> AppCompatActivity.createViewModel(crossinline factory: () -> T): T = T::class.java.let { clazz ->
    ViewModelProviders.of(this, object: ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            if(modelClass == clazz) {
                @Suppress("UNCHECKED_CAST")
                return factory() as T
            }
            throw IllegalArgumentException("Unexpected argument: $modelClass")
        }
    }).get(clazz)
}

现在可以让你做到

brandsViewModel = createViewModel { singletonComponent.brandsViewModel() }

现在BrandsViewModel可以从Dagger接收参数:

class BrandsViewModel @Inject constructor(
    private val appContext: Context,
    /* other deps */
): ViewModel() {
    ...
}

答案 1 :(得分:6)

答案基于android-architecture-components

您可以在Dagger中使用Map multibinding。

首先,像这样声明地图密钥。

@MustBeDocumented
@Target(
    AnnotationTarget.FUNCTION,
    AnnotationTarget.PROPERTY_GETTER,
    AnnotationTarget.PROPERTY_SETTER
)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)

第二,创建地图。

@Module
abstract class ViewModelModule {
    @Binds
    @IntoMap
    @ViewModelKey(UserViewModel::class)
    abstract fun bindUserViewModel(userViewModel: UserViewModel): ViewModel

    @Binds
    @IntoMap
    @ViewModelKey(SearchViewModel::class)
    abstract fun bindSearchViewModel(searchViewModel: SearchViewModel): ViewModel
}

接下来,创建工厂文件以处理使用键选择ViewModel的地图。

@Singleton
class GithubViewModelFactory @Inject constructor(
    private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        val creator = creators[modelClass] ?: creators.entries.firstOrNull {
            modelClass.isAssignableFrom(it.key)
        }?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
        try {
            @Suppress("UNCHECKED_CAST")
            return creator.get() as T
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }
}

最后,在您的活动或片段中注入工厂。

class SearchFragment : Fragment(), Injectable {

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        searchViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(SearchViewModel::class.java)
}

通过这种方式,您可以在ViewModel中注入存储库。

class SearchViewModel @Inject constructor(repoRepository: RepoRepository) : ViewModel() {
}