ViewModel的许多实例,如何解决?

时间:2019-07-12 22:17:55

标签: android mvvm viewmodel

我通过this example创建了ViewModelFactory:

Public Function GetColumnNumber(ByVal WksN As String, _
                                ByVal hdr As String) As Long
    Dim f As Range

    Set f = ActiveWorkbook.Worksheets(WksN).Rows(1).Find( _
                    what:=hdr, LookIn:=xlValues, lookat:=xlPart)

    If f Is Nothing Then
        GetColumnNumber = 0
    Else
        GetColumnNumber = f.Column
    End If
End Function

在“活动”中,我创建ViewModel的实例:

public class ViewModelFactory extends ViewModelProvider.NewInstanceFactory {
    @SuppressLint("StaticFieldLeak")
    private static volatile ViewModelFactory INSTANCE;

    private final Application application;

    public static ViewModelFactory getInstance(Application application) {
        if (INSTANCE == null) {
            synchronized (ViewModelFactory.class) {
                if (INSTANCE == null) {
                    INSTANCE = new ViewModelFactory(application);
                }
            }
        }
        return INSTANCE;
    }

    private ViewModelFactory(Application application) {
        this.application = application;
    }

    @Override
    public <T extends ViewModel> T create(Class<T> modelClass) {

        if (modelClass.isAssignableFrom(MyViewModel.class)) {
            //noinspection unchecked
            return (T) new MyViewModel(
                    Repository.getInstance(
                            RemoteDataSource.getInstance(WebService.getInstance().getWebServiceApi()),
                            LocalDataSource.getInstance(new AppExecutors(), MyDatabase.getInstance(application).myDao())
                    )
            );
        }

        throw new IllegalArgumentException("Unknown ViewModel class: " + modelClass.getName());
    }
}

然后,我想在片段中使用MyViewModel并按照this example进行操作:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Log.d(TAG, "onCreate");

    if (savedInstanceState == null) {
        myViewModel = ViewModelProviders.of(this, ViewModelFactory.getInstance(this.getApplication())).get(MyViewModel.class);
    }
}

public class Fragment1 extends Fragment {
...

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        myViewModel = ViewModelProviders.of(this, ViewModelFactory.getInstance(getActivity().getApplication())).get(MyViewModel.class);

        ...
    }
}

问题在于创建片段时,将创建MyViewModel的新实例(我在日志中的MyViewModel构造函数中看到了此信息,显示“ New MyViewModel Instanced Created”)。随着每个新片段的打开,我在日志中看到“ New MyViewModel Instance Created”。

请帮助我,了解如何解决此问题?

1 个答案:

答案 0 :(得分:0)

您正在使用ViewModelProviders.of(this, ...)。这意味着您需要与该特定Fragment关联的ViewModel实例。

如果要与活动关联的ViewModel实例,则应在Fragments中使用ViewModelProviders.of(requireActivity(), ...)