How To Get Viewmodel In Background Service Android
ViewModel Overview Part of Android Jetpack.
The ViewModel class is designed to shop and manage UI-related information in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.
The Android framework manages the lifecycles of UI controllers, such as activities and fragments. The framework may decide to destroy or copy a UI controller in response to certain user actions or device events that are completely out of your control.
If the system destroys or re-creates a UI controller, any transient UI-related data you store in them is lost. For example, your app may include a list of users in one of its activities. When the activity is re-created for a configuration alter, the new activity has to re-fetch the listing of users. For uncomplicated data, the activity tin utilise the onSaveInstanceState() method and restore its data from the bundle in onCreate(), but this approach is only suitable for small amounts of data that can be serialized then deserialized, not for potentially big amounts of data similar a list of users or bitmaps.
Another problem is that UI controllers frequently demand to brand asynchronous calls that may take some time to return. The UI controller needs to manage these calls and ensure the system cleans them up after it's destroyed to avoid potential memory leaks. This direction requires a lot of maintenance, and in the case where the object is re-created for a configuration alter, it's a waste of resources since the object may have to reissue calls it has already made.
UI controllers such as activities and fragments are primarily intended to display UI data, react to user actions, or handle operating system advice, such as permission requests. Requiring UI controllers to likewise be responsible for loading information from a database or network adds bloat to the course. Assigning excessive responsibility to UI controllers can effect in a unmarried class that tries to handle all of an app'south work by itself, instead of delegating work to other classes. Assigning excessive responsibility to the UI controllers in this manner also makes testing a lot harder.
Information technology's easier and more efficient to separate out view data ownership from UI controller logic.
Implement a ViewModel
Compages Components provides ViewModel helper course for the UI controller that is responsible for preparing data for the UI. ViewModel objects are automatically retained during configuration changes and then that data they concur is immediately bachelor to the next activity or fragment example. For case, if you need to brandish a list of users in your app, make certain to assign responsibility to learn and go on the listing of users to a ViewModel, instead of an activeness or fragment, as illustrated by the post-obit sample code:
Kotlin
course MyViewModel : ViewModel() { private val users: MutableLiveData<Listing<User>> past lazy { MutableLiveData<Listing<User>>().also { loadUsers() } } fun getUsers(): LiveData<List<User>> { render users } private fun loadUsers() { // Do an asynchronous functioning to fetch users. } } Java
public class MyViewModel extends ViewModel { private MutableLiveData<List<User>> users; public LiveData<List<User>> getUsers() { if (users == null) { users = new MutableLiveData<List<User>>(); loadUsers(); } return users; } private void loadUsers() { // Do an asynchronous functioning to fetch users. } } You can then admission the list from an action as follows:
Kotlin
class MyActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { // Create a ViewModel the offset time the organization calls an activeness's onCreate() method. // Re-created activities receive the same MyViewModel instance created by the first action. // Employ the 'by viewModels()' Kotlin belongings consul // from the activity-ktx antiquity val model: MyViewModel by viewModels() model.getUsers().observe(this, Observer<List<User>>{ users -> // update UI }) } } Java
public course MyActivity extends AppCompatActivity { public void onCreate(Package savedInstanceState) { // Create a ViewModel the first time the system calls an activity's onCreate() method. // Re-created activities receive the aforementioned MyViewModel instance created by the first action. MyViewModel model = new ViewModelProvider(this).get(MyViewModel.class); model.getUsers().discover(this, users -> { // update UI }); } } If the activity is re-created, it receives the same MyViewModel case that was created past the get-go activity. When the owner activity is finished, the framework calls the ViewModel objects's onCleared() method so that information technology can clean up resource.
ViewModel objects are designed to outlive specific instantiations of views or LifecycleOwners. This design besides means you lot tin write tests to cover a ViewModel more than easily as it doesn't know about view and Lifecycle objects. ViewModel objects can contain LifecycleObservers, such every bit LiveData objects. Notwithstanding ViewModel objects must never find changes to lifecycle-aware observables, such as LiveData objects. If the ViewModel needs the Awarding context, for case to detect a arrangement service, it tin can extend the AndroidViewModel class and accept a constructor that receives the Application in the constructor, since Application class extends Context.
The lifecycle of a ViewModel
ViewModel objects are scoped to the Lifecycle passed to the ViewModelProvider when getting the ViewModel. The ViewModel remains in retentiveness until the Lifecycle it's scoped to goes away permanently: in the instance of an activity, when information technology finishes, while in the case of a fragment, when it's discrete.
Figure 1 illustrates the various lifecycle states of an activity every bit it undergoes a rotation and and so is finished. The illustration also shows the lifetime of the ViewModel next to the associated activity lifecycle. This particular diagram illustrates united states of an activity. The same basic states employ to the lifecycle of a fragment.
Yous usually request a ViewModel the starting time time the system calls an activity object'south onCreate() method. The system may call onCreate() several times throughout the life of an activity, such as when a device screen is rotated. The ViewModel exists from when you first asking a ViewModel until the activity is finished and destroyed.
Share data between fragments
It'due south very common that two or more fragments in an activeness demand to communicate with each other. Imagine a common example of separate-view (list-detail) fragments, where y'all have a fragment in which the user selects an detail from a list and another fragment that displays the contents of the selected item. This case is never trivial as both fragments demand to ascertain some interface description, and the owner activity must demark the ii together. In add-on, both fragments must handle the scenario where the other fragment is not yet created or visible.
This common hurting point can be addressed past using ViewModel objects. These fragments tin can share a ViewModel using their activity scope to handle this communication, as illustrated by the following sample code:
Kotlin
class SharedViewModel : ViewModel() { val selected = MutableLiveData<Item>() fun select(detail: Detail) { selected.value = item } } class ListFragment : Fragment() { private lateinit var itemSelector: Selector // Use the 'past activityViewModels()' Kotlin holding consul // from the fragment-ktx artifact private val model: SharedViewModel by activityViewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) itemSelector.setOnClickListener { item -> // Update the UI } } } class DetailFragment : Fragment() { // Use the 'by activityViewModels()' Kotlin holding delegate // from the fragment-ktx artifact private val model: SharedViewModel by activityViewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) model.selected.observe(viewLifecycleOwner, Observer<Item> { item -> // Update the UI }) } } Java
public class SharedViewModel extends ViewModel { private concluding MutableLiveData<Detail> selected = new MutableLiveData<Particular>(); public void select(Item item) { selected.setValue(particular); } public LiveData<Detail> getSelected() { return selected; } } public course ListFragment extends Fragment { private SharedViewModel model; public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); model = new ViewModelProvider(requireActivity()).become(SharedViewModel.grade); itemSelector.setOnClickListener(item -> { model.select(item); }); } } public class DetailFragment extends Fragment { public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); SharedViewModel model = new ViewModelProvider(requireActivity()).become(SharedViewModel.course); model.getSelected().observe(getViewLifecycleOwner(), item -> { // Update the UI. }); } } Notice that both fragments retrieve the activity that contains them. That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activeness.
This approach offers the following benefits:
- The activity does not need to exercise anything, or know anything about this communication.
- Fragments don't need to know about each other besides the
SharedViewModelcontract. If one of the fragments disappears, the other ane keeps working as usual. - Each fragment has its own lifecycle, and is not affected by the lifecycle of the other 1. If 1 fragment replaces the other 1, the UI continues to piece of work without any problems.
Replacing Loaders with ViewModel
Loader classes similar CursorLoader are oft used to proceed the information in an app's UI in sync with a database. You tin can use ViewModel, with a few other classes, to replace the loader. Using a ViewModel separates your UI controller from the data-loading functioning, which ways you accept fewer potent references between classes.
In one common approach to using loaders, an app might utilize a CursorLoader to observe the contents of a database. When a value in the database changes, the loader automatically triggers a reload of the data and updates the UI:
ViewModel works with Room and LiveData to replace the loader. The ViewModel ensures that the data survives a device configuration change. Room informs your LiveData when the database changes, and the LiveData, in plow, updates your UI with the revised data.
Employ coroutines with ViewModel
ViewModel includes support for Kotlin coroutines. For more information, see Use Kotlin coroutines with Android Architecture Components.
Further data
Every bit your information grows more complex, you might cull to have a dissever class just to load the data. The purpose of ViewModel is to encapsulate the information for a UI controller to let the information survive configuration changes. For data about how to load, persist, and manage data beyond configuration changes, see Saving UI States.
The Guide to Android App Architecture suggests edifice a repository grade to handle these functions.
Additional resources
For farther data about the ViewModel grade, consult the following resources.
Samples
- Android Architecture Components basic sample
- Sunflower, a gardening app illustrating Android development best practices with Android Jetpack.
Codelabs
- Android Room with a View (Coffee) (Kotlin)
- Android lifecycle-aware components codelab
Blogs
- ViewModels : A Simple Example
- ViewModels: Persistence, onSaveInstanceState(), Restoring UI Country and Loaders
- ViewModels and LiveData: Patterns + AntiPatterns
- Kotlin Demystified: Understanding Autograph Lambda Syntax
- Kotlin Demystified: Scope functions
- Kotlin Demystified: When to apply custom accessors
- Lifecycle Enlightened Information Loading with Architecture Components
Videos
- Android Jetpack: ViewModel
How To Get Viewmodel In Background Service Android,
Source: https://developer.android.com/topic/libraries/architecture/viewmodel
Posted by: conradforearephe.blogspot.com

0 Response to "How To Get Viewmodel In Background Service Android"
Post a Comment