简体   繁体   English

在另一个活动中加载ViewModel实例

[英]Load ViewModel instance in another activity

When app start I need to download data and populate all viewModels to avoid slowdowns during the app usage. 应用程序启动时,我需要下载数据并填充所有viewModel,以避免在应用程序使用过程中速度变慢。 First activity is: 第一项活动是:

public class MainActivity extends AppCompatActivity {
private MainViewModel mainViewModel;

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

         mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);

   }
}

I'm thinking to create in the activity above the instance of the other activity's viewModel and pass it through the intent. 我正在考虑在活动中创建另一个活动的viewModel实例的实例,并将其传递给意图。 I'm not sure if is it right to create the instance of a viewModel not in its consistent activity. 我不确定不是在其一致的活动中创建viewModel的实例是否正确。

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. ViewModel类旨在以生命周期感知的方式存储和管理与UI相关的数据。

If you want to share any data between your viewModels, the best idea would be creating a singleton data source and provide it inside of viewModels, such as SharedPreferences , sqlite datase, etc. 如果要在viewModel之间共享任何数据,最好的方法是创建一个singleton数据源,并将其提供到viewModel内部,例如SharedPreferencessqlite datase等。

If you really need to use a viewModel as your data source you can create a singletone instance of it by implementing a custom ViewModelFactory which has been already discussed in this github issue : 如果你真的需要使用视图模型作为数据源,你可以创建一个singletone通过实现自定义它的实例ViewModelFactory已在此github上已经被讨论的问题

you can use factory to make viewmodel and this factor will return single object of view model.. As: 您可以使用factory来创建viewmodel,并且此因子将返回视图模型的单个对象。

class ViewModelFactory() : ViewModelProvider.Factory {

    override fun create(modelClass: Class): T {
        if (modelClass.isAssignableFrom(UserProfileViewModel::class.java)) {
            val key = "UserProfileViewModel"
            if(hashMapViewModel.containsKey(key)) {
                return getViewModel(key) as T
            } else {
                addViewModel(key, UserProfileViewModel())
            return getViewModel(key) as T
        }
    }
    throw IllegalArgumentException("Unknown ViewModel class")
    }

    companion object {
        val hashMapViewModel = HashMap<String, ViewModel>()

        fun addViewModel(key: String, viewModel: ViewModel) {
            hashMapViewModel.put(key, viewModel)
        }

        fun getViewModel(key: String): ViewModel? {
            return hashMapViewModel[key]
        }
    }
}

In Activity: 活动中:

viewModelFactory = Injection.provideViewModelFactory(this)

// Initialize Product View Model
userViewModel = ViewModelProviders.of(this,viewModelFactory).get(UserProfileViewModel::class.java)

This will provide only single object of UserProfileViewModel which you can share between Activities. 这将仅提供UserProfileViewModel的单个对象,您可以在Activity之间共享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ViewModel 实例 - Activity UI - Android 架构组件 - ViewModel instance - Activity UI - Android Architecture Components 将 viewmodel 实例传递给另一个 class 并从该 class 调用 viewmodel.update()、viewmodel.insert() 和其他函数 - Pass viewmodel instance to another class and call viewmodel.update(), viewmodel.insert() and other functions from that class 如何从另一个活动刷新 viewModel 实时数据 - How can I refresh viewModel livedata from another activity 定时加载另一项活动需要多长时间 - Timer how long it takes to load another activity 将Android启动活动更改为另一个活动= app无法加载 - Changing Android launch activity to another activity = app doesn't load 在一个活动中将 Arraylist 保存到 sharedpreferences 并在另一个活动中将其加载到 recyclerview - Save Arraylist into sharedpreferences in one activity and load it in recyclerview in another activity 如何在活动中加载插页式广告并在其他活动中显示? - How can i load interstitial ad in activity and show is in another activity? 如何将 Activity 传递给 ViewModel? - How to pass Activity to the ViewModel? ListView 不会加载有关第一个 Activity 实例的信息 - ListView won't load information on the first instance of Activity 无法创建 ViewModel 的实例 - Unable to create an instance of ViewModel
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM