2

我正在尝试在我现有的项目中实现新架构(MVVM + RxJava2 + Dagger2 + Retrofit)。我已经建立了整个以上架构并在 HomeActivity 上进行了测试。在 HomeViewModel 中注入的依赖项。所以现在我试图在 FollowFragment 的 FollowViewModel 中注入与 HomeViewModel 相同的依赖项,这是 HomeActivity 的容器片段。但是注入的依赖项总是返回 null(不是 Initiziling)。

我正在关注这个项目riggaroo/android-arch-components-date-countdown来注入依赖项,但在这个示例中,只使用活动而不使用片段。所以我不知道发生了什么以及谁在多个 ViewModel 中注入 deps。

以下是一些需要理解的重要类的代码:

AppApplication.class

 public class AppApplication extends MultiDexApplication implements HasActivityInjector {
@Inject
    DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;
@Override
    public void onCreate() {
        ...........................
        AppInjector.init(this)
        ..........................
    }
    @Override
    public AndroidInjector<Activity> activityInjector() {
        return dispatchingAndroidInjector;
    }
}

AppInjector.class

public class AppInjector {
private AppInjector() {
}

public static void init(AppApplication appApplication) {
    DaggerAppComponent.builder()
            .application(appApplication)
            .build()
            .inject(appApplication);
            appApplication
            .registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                    handleActivity(activity);
                }

            });
}

private static void handleActivity(Activity activity) {
    if (activity instanceof HasSupportFragmentInjector) {
        AndroidInjection.inject(activity);
    }
    if (activity instanceof FragmentActivity) {
        ((FragmentActivity) activity).getSupportFragmentManager()
                .registerFragmentLifecycleCallbacks(
                        new FragmentManager.FragmentLifecycleCallbacks() {
                            @Override
                            public void onFragmentCreated(FragmentManager fm, Fragment f,
                                                          Bundle savedInstanceState) {
                                if (f instanceof Injectable) {
                                    AndroidSupportInjection.inject(f);
                                }
                            }
                        }, true);
    }
}
}

应用组件类

@Singleton
@Component(modules = {AndroidSupportInjectionModule.class,ActivityBuilderModule.class, AppModule.class, NetworkModule.class})
public interface AppComponent {
@Component.Builder
interface Builder {
    @BindsInstance
    Builder application(AppApplication application);

    AppComponent build();

}
void inject(AppApplication app);

应用模块类

@Module(includes = { ViewModelModule.class})
public class AppModule {
    @Provides
    Context provideContext(AppApplication application) {
        return application.getApplicationContext();
    }
}

ActivityBuilderModule.class

@Module
public abstract class ActivityBuilderModule {
@ContributesAndroidInjector(modules = FragmentBuildersModule.class)
abstract HomeActivity bindHomeActivity();
}

FragmentBuildersModule.class

@Module
public abstract class FragmentBuildersModule {
@ContributesAndroidInjector
abstract FollowingListFragment contributeFollowingListFragment();
}

ViewModule.class

@Module
public abstract class ViewModelModule {
    @Binds
    @IntoMap
    @ViewModelKey(FollowingViewModel.class)
    abstract ViewModel bindFollowingViewModel(FollowingViewModel followingViewModel);

    @Binds
    @IntoMap
    @ViewModelKey(HomeViewModel.class)
    abstract ViewModel bindHomeViewModel(HomeViewModel homeViewModel);

    @Binds
    abstract ViewModelProvider.Factory bindViewModelFactory(MyViewModelFactory factory);

}

NetworkModule.class

 @Module
public class NetworkModule {
    public NetworkModule(){}
    @Provides
    @Singleton
    CompositeDisposable getCompositeDisposable() {
        return new CompositeDisposable();
    }
    @Provides
    @Singleton
    Retrofit provideCall() {
        // OKHttps and Retrofit code...
    }
    @Provides
    @Singleton
    @SuppressWarnings("unused")
    public ApiCallInterface providesNetworkService(
            Retrofit retrofit) {
        return retrofit.create(ApiCallInterface.class);
    }
    @Provides
    @Singleton
    @SuppressWarnings("unused")
    public Repository providesService(
            ApiCallInterface networkService) {
        return new Repository(networkService);
    }
}

MyViewModelFactory.class

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

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

@SuppressWarnings("unchecked")
@Override
public <T extends ViewModel> T create(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);
    }
}
}

此类用于创建所有视图模型的实例。我已经调试并发现只有 HomeViewModel 实例正在创建。

现在我创建了从 HomeActivity 调用的 HomeViewModel。哪个工作正常。现在在 FollowFragment 中完成了相同的实现,但不起作用。让我向您展示我如何从 FollowListFragment.class 初始化 FollowViewModel

public class FollowingListFragment extends BaseFragment implementsInjectable {
    @Inject
    MyViewModelFactory myViewModelFactory;
    private FollowingViewModel followingViewModel;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
followingViewModel = ViewModelProviders.of(this, plownsViewModelFactory)
                .get(FollowingViewModel.class);
}

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_following_list, container, false);
    }

@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        followingViewModel.getFollowings(id,curser);
 }
}

这是FollowingViewModel.class

public class FollowingViewModel extends ViewModel {
@Inject
Repository service;
@Inject
CompositeDisposable subscriptions;

@Inject
public FollowingViewModel() {
}

/*void setService(Repository service){
    this.service = service;
}*/

void getFollowings(String id,String curser) {
    if(service!=null) { **//HERE SERVICE RETURNS NULL** 
        Disposable subscription = service.getFollowings(id, curser, new IResponseCallback<FollowingResponse.FollowingResult>() {
            @Override
            public void onSuccess(FollowingResponse.FollowingResult followingResult) {
            }
            @Override
            public void onError(Throwable throwable) {
            }
        });
        subscriptions.add(subscription);
    }else {
        Log.d("FollowViewModel", "Service is null " );
    }
}

这是工作正常的 HomeActivity 和 HomeViewModel 类代码。HomeActivity.class

public class HomeActivity extends BaseActivity implements HasSupportFragmentInjector, Injectable {

    @Inject
    DispatchingAndroidInjector<Fragment> supportFragmentInjector;
    @Inject
    MyViewModelFactory viewFactory;
    HomeViewModel homeViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    homeViewModel = ViewModelProviders.of(this,viewFactory).get(HomeViewModel.class);
        homeViewModel.getFollowings("xyx",null);
 }
 @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return supportFragmentInjector;
    }
}

HomeViewModel.class

public class HomeViewModel extends ViewModel {
    @Inject
    Repository service;
    @Inject
    CompositeDisposable subscriptions;
    @Inject
    public HomeViewModel() {

    }

    void getFollowings(String id,String curser) {
        if(service!=null) { **// Returing null service**
}
    }else {
            Log.d("FollowViewModel", "Service is null " );
        }
}
}
4

0 回答 0