In Android development, ViewModel is part of the Android Architecture Components and is designed to store and manage UI-related data in a lifecycle-conscious way. This ensures that data survives configuration changes such as screen rotations. ViewModels allow for better separation of concerns, enabling developers to manage and access their data efficiently within Activity and Fragment lifecycles.
Internally, ViewModel works by extending the ViewModel class and is initialized in a way that lifecycle-aware components can access it. The ViewModel is tied to the lifecycle of the activity or fragment, which means it will be retained as long as the scope is valid, allowing data to be preserved across configuration changes.
Here is a simple example to illustrate how to implement a ViewModel in an Android application:
// MyViewModel.java
public class MyViewModel extends ViewModel {
private MutableLiveData data;
public LiveData getData() {
if (data == null) {
data = new MutableLiveData<>();
loadData();
}
return data;
}
private void loadData() {
// Load data logic here (could be from a database or network)
data.setValue("Hello, ViewModel!");
}
}
// MainActivity.java
public class MainActivity extends AppCompatActivity {
private MyViewModel myViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myViewModel = new ViewModelProvider(this).get(MyViewModel.class);
myViewModel.getData().observe(this, new Observer() {
@Override
public void onChanged(String s) {
// Update UI with the data
}
});
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?