Bill
11/03/2022, 2:11 PMChris Lee
11/03/2022, 2:15 PMBill
11/03/2022, 2:18 PMChris Lee
11/03/2022, 2:21 PMBill
11/03/2022, 2:23 PMRobert Williams
11/03/2022, 2:31 PMBill
11/03/2022, 2:35 PMBill
11/03/2022, 2:37 PMCasey Brooks
11/03/2022, 2:47 PMActivity
to the ViewModel
, but thereâs a lot more benefit when you use it as part of an Architecture Design Pattern like MVVM or MVI.
ViewModels specifically work with in-memory data, and it should generally be considered ephemeral. That is, the data stored in your ViewModel sticks around for only 1 app session, and youâd need to reload it the next time the user opens the app (or on other conditions that are shorter than the entire session, depending on your appâs navigation). For anything that needs to be persisted longer than the lifetime of the ViewModel (such as across app launches), youâd need to store it in a persistent way, such as with DataStore or RoomBill
11/03/2022, 2:54 PMCasey Brooks
11/03/2022, 3:02 PMContactsViewModel
and use the Android facilities to get an instance of it in your ContactsActivity
2. Observe your Realm query as a Flow
within the ViewModelâs viewModelScope
(see docs). Whenever the query updates, save the query results somewhere within the ViewModel such as a StateFlow
3. Your ContactsActivity
should collect the ViewModelâs StateFlow
from within its lifecycleScope
.
Thus, the whole pipeline becomes âRealm > ViewModel > Activityâ, but everything is being done safely and is managed, such that if you leave the Activity youâre no longer wasting resources or leaking memory from db subscriptions that are not actively visible on the screenBill
11/03/2022, 3:04 PMCasey Brooks
11/03/2022, 3:09 PMRobert Williams
11/03/2022, 3:13 PMCasey Brooks
11/03/2022, 3:18 PMBill
11/03/2022, 3:25 PMCasey Brooks
11/03/2022, 3:33 PMmiqbaldc
11/04/2022, 3:10 AM