According to the information I can find, the MvvmCross Viewmodel life cycle is
Construction - using IoC for Dependency Injection
Init() - initialisation of navigation parameters
ReloadState() - rehydration after tombstoning
Start() - called when initialisation and rehydration are complete
I have implemented mine as follows:
public async Task Init(Guid ID)
{
await MPS_Mobile_Driver.Droid.DataModel.ShipmentDataSource.GetShipmentInventory(ID);
ShipmentInventory = ShipmentDataSource.CurrInventory;
ShipmentLots = await MPS_Mobile_Driver.Droid.DataModel.ShipmentDataSource.GetShipmentLotList((int)ShipmentInventory.idno, (short)ShipmentInventory.idsub);
Inv_DamageList = await ListDataSource.GetInv_Damage();
}
protected override void SaveStateToBundle(IMvxBundle bundle)
{
base.SaveStateToBundle(bundle);
bundle.Data["ShipmentInventory"] = StringSerializer.SerializeObject(ShipmentInventory);
bundle.Data["ShipmentLots"] = StringSerializer.SerializeObject(ShipmentLots);
bundle.Data["Inv_DamageList"] = StringSerializer.SerializeObject(Inv_DamageList);
}
protected override void ReloadFromBundle(IMvxBundle state)
{
base.ReloadFromBundle(state);
ShipmentInventory = StringSerializer.DeserializeObject<ShipmentInventory>(state.Data["ShipmentInventory"]);
ShipmentLots = StringSerializer.DeserializeObject<ShipmentLotList>(state.Data["ShipmentLots"]);
Inv_DamageList = StringSerializer.DeserializeObject<Inv_DamageList>(state.Data["Inv_DamageList"]);
state.Data.Clear();
}
First off, I can't seem to get the emulator to actually destroy the Activity when I hit the Home key even though I have that option checked. The activity seems to hang around in the background anyway.
That being said, when I do hit the home key, It calls SaveStateToBundle. What it never seems to do is to call ReloadFromBundle. This makes it hard to test What is actually going on. My fear is that according to the life cycle, if the app does recover from a tombstone, it will call Init before it calls ReloadFromBundle. Since Init is the preferred way to pass a parameter to a ViewModel, it only makes sense to it should use the parameter to initialize the data. If after this happens, it calls ReloadFromBundle, It would overwrite the data initialized in Init. This is fine but very inefficient. Is there a way to know in Init if the ViewModel is being created due to a new navigation or if it is recovering from a tombstone?
Thanks for any help with this.
Jim
I have the same issue with ReloadFromBundle(IMvxBundle state), it is never called. Only the "SaveState" pattern seems to work.
I can answer to your second question though:
You shouldn't use Init to load your data. You should only use it to pass ids of data to be retrieved. The "loading" phase should happen in the Start method.
Related
I am trying first handle the response from API by using observe. Later after observing the handled variable I want to save it to database.
The variable tokenFromApi is updated inside tokenResponseFromApi's observer. Is it possible to observe tokenFromApi outside the observer of tokenResponseFromApi? When debugged, the code did not enter inside tokenFromApi observer when the app started.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
var tokenResponseFromApi: LiveData<String>? = MutableLiveData<String>()
var tokenFromApi: LiveData<TokenEntity>? = MutableLiveData<TokenEntity>()
tokenResponseFromApi?.observe(viewLifecycleOwner, Observer {
tokenResponseFromApi ->
if (tokenResponseFromApi != null) {
tokenFromApi = viewModel.convertTokenResponseToEntity(tokenResponseFromApi, dh.asDate)
}
})
tokenFromApi?.observe(viewLifecycleOwner, Observer {
tokenFromApi ->
if (tokenFromApi != null) {
viewModel.saveTokenToDB(repo, tokenFromApi)
}
})
}
Your problem is that you're registering the observer on tokenFromApi during setup, and when you get your API response, you're replacing tokenFromApi without registering an observer on it. So if it ever emits a value, you'll never know about it. The only observer you have registered is the one on the discarded tokenFromApi which is never used by anything
Honestly your setup here isn't how you're supposed to use LiveData. Instead of creating a whole new tokenFromApi for each response, you'd just have a single LiveData that things can observe. When there's a new value (like an API token) you set that on the LiveData, and all the observers see it and react to it. Once that's wired up, it's done and it all works.
The way you're doing it right now, you have a data source that needs to be taken apart, replaced with a new one, and then everything reconnected to it - every time there's a new piece of data, if you see what I mean.
Ideally the Fragment is the UI, so it reacts to events (by observing a data source like a LiveData and pushes UI events to the view model (someone clicked this thing, etc). That API fetching and DB storing really belongs in the VM - and you're already half doing that with those functions in the VM you're calling here, right? The LiveDatas belong in the VM because they're a source of data about what's going on inside the VM, and the rest of the app - they expose info the UI needs to react to. Having the LiveData instances in your fragment and trying to wire them up when something happens is part of your problem
Have a look at the App Architecture guide (that's the UI Layer page but it's worth being familiar with the rest), but this is a basic sketch of how I'd do it:
class SomeViewModel ViewModel() {
// private mutable version, public immutable version
private val _tokenFromApi = MutableLiveData<TokenEntity>()
val tokenFromApi: LiveData<TokenEntity> get() = _tokenFromApi
fun callApi() {
// Do your API call here
// Whatever callback/observer function you're using, do this
// with the result:
result?.let { reponse ->
convertTokenResponseToEntity(response, dh.asDate)
}?.let { token ->
saveTokenToDb(repo, token)
_tokenFromApi.setValue(token)
}
}
private fun convertTokenResponseToEntity(response: String, date: Date): TokenEntity? {
// whatever goes on in here
}
private fun saveTokenToDb(repo: Repository, token: TokenEntity) {
// whatever goes on in here too
}
}
so it's basically all contained within the VM - the UI stuff like fragments doesn't need to know anything about API calls, whether something is being stored, how it's being stored. The VM can update one of its exposed LiveData objects when it needs to emit some new data, update some state, or whatever - stuff that's interesting to things outside the VM, not its internal workings. The Fragment just observes whichever one it's interested in, and updates the UI as required.
(I know the callback situation might be more complex than that, like saving to the DB might involve a Flow or something. But the idea is the same - in its callback/result function, push a value to your LiveData as appropriate so observers can receive it. And there's nothing wrong with using LiveData or Flow objects inside the VM, and wiring those up so a new TokenEntity gets pushed to an observer that calls saveTokenToDb, if that kind of pipeline setup makes sense! But keep that stuff private if the outside world doesn't need to know about those intermediate steps
I am trying to figure out how jobs with coroutines work. Basically, I want to launch this coroutine from FirstFragment and after that navigate to SecondFragment and get notified when this job is done. I call getData() in FirstFragment onViewCreated() and navigate to SecondFragment. Whether I write getData().isCompleted or getData().invokeOnCompletion { } in SecondFragment nothing happens. I don't know if I am missing something or not starting job correctly or something else.
private val _data = MutableStateFlow<GetResource<String>?>(null)
val data: StateFlow<GetResource<String>?> = _data
fun getData() = viewModelScope.launch {
repository.getData().collect {
_data.value = it
}
}
A Flow from a database never completes because it is supposed to monitor the database for changes indefinitely. It only stops when the coroutine is cancelled. Therefore the Job that collects such a Flow will never complete. Also, if you call getData() on the repo again, you are getting a new Flow instance each time.
Regardless of what you're doing, you need to be sure you are using the same ViewModel instance between both fragments by scoping it to the Activity. (Use by activityViewModels() for example.) This is so the viewModelScope won't be cancelled during the transition between Fragments.
If all you need is a single item from the repo one time, probably the simplest thing to do would be to expose a suspend function from the repo instead of a Flow. Then turn it into a Deferred. Maybe by making it a Lazy, you can selectively decide when to start retrieving the value. Omit the lazy if you just want to start retrieving the value immediately when the first Fragment starts.
// In the shared view model:
val data: Deferred<GetResource<String>> by lazy {
viewModelScope.async {
repository.getData() // suspend function returning GetResource<String>
}
}
fun startDataRetrieval() { data } // access the lazy property to start its coroutine
// In second fragment:
lifecycleScope.launch {
val value = mySharedViewModel.data.await()
// do something with value
}
But if you have to have the Flow because you’re using it for other purposes:
If you just want the first available value from the Flow, have the second Fragment monitor your data StateFlow for its first valid value.
lifecycleScope.launch {
val value = mySharedViewModel.data.filterNotNull().first()
// do something with first arrived value
}
And you can use SharedFlow so you don’t have to make the data type nullable. If you do this you can omit filterNotNull() above. In your ViewModel, it’s easier to do this with shareIn than your code that has to use a backing property and manually collect the source.
val data: SharedFlow<GetResource<String>> = repository.getData()
.shareIn(viewModelScope, replay = 1, SharingStarted.Eagerly)
If you need to wait before starting the collection to the SharedFlow, then you could make the property lazy.
Agreed with #Tenfour04 's answer, I would like to contribute a little more.
If you really want to control over the jobs or Structured Concurrency, i would suggest use custom way of handling the coroutine rather than coupled your code with the viewModelScope.
There are couple of things you need to make sure:
1- What happen when cancellation or exception occurrs
2- you have to manage the lifecycle of the coroutine(CoroutineScope)
3- Cancelling scope, depends on usecase like problem facing you are right now
4- Scope of ViewModel e.g: Either it is tied to activity(Shared ViewModel) or for specific fragment.
If you are not handling either of these carefully specifically first 3, your are more likely to leaking the coroutine your are gurenteed gonna get misbehavior of you app.
Whenever you start any coroutine in Custom way you have to make sure, what is going to be the lifecycle, when it gonna end, This is so important, it can cause real problems
Luckily, i have this sample of CustomViewModel using Jobs: Structured Concurrency sample code
So currently I have a Dao with a function that emits a Flow<>
#Query("SELECT * FROM ${Constants.Redacted}")
fun loadAllContacts(): Flow<List<Redacted>>
I am calling this from a repository like so
val loadAllContacts: Flow<List<Redacted>> = contactDao.loadAllContacts()
I am injecting the repository into the viewModel's constructor, and then at the top of my viewModel I have a val like so
val contacts: LiveData<List<Redacted>> = contactRepository.loadAllContacts.asLiveData()
Which is being observed in my Activity like so
viewModel.contacts.observe(this) { contacts ->
viewModel.onContactsChange(contacts)
}
My thinking is that the Flow is converted to a LiveData, and then I can observe this LiveData from my activity and kick off this function to actually update the viewModel upon the data being updated.
For now onContactsChange just looks like
fun onContactsChange(list: List<Redacted>) {
Timber.i("VIEW UPDATE")
}
The problem is that I only see this Timber log upon opening the activity, and never again. I verified that data IS going into my database, and I verified that an insert occurred successfully while the activity & viewModel are open. But I never see the log from onContactsChange again. When I close the activity, and reopen it, I do see my new data, so that is another reason I know my insert is working correctly.
I would like to add that I am using a single instance (singleton) of my repository, and I think I can verify this by the fact that I can see my data at all, at least when the view is first made.
Figured it out:
Note: If your app runs in a single process, you should follow the singleton design pattern when instantiating an AppDatabase object. Each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances within a single process.
If your app runs in multiple processes, include enableMultiInstanceInvalidation() in your database builder invocation. That way, when you have an instance of AppDatabase in each process, you can invalidate the shared database file in one process, and this invalidation automatically propagates to the instances of AppDatabase within other processes.
It's a little bit hard to follow your question, but I think I see the overall problem with your Flow object not updating the way you want it too.
Following this quick tutorial, it seems that first you should declare your Flow object inside your Repository the same way you're already doing
val loadAllContacts: Flow<List<Redacted>> = contactDao.loadAllContacts()
and have your VM 'subscribe' to it by using the collect coroutine which would then allow you to dump all this data into a MutableLiveData State
data class YourState(..)
val state = MutableLiveData<YourState>()
init {
contactRepository.loadAllContacts().collect {
if (it.isNotEmpty()) {
state.postValue(YourState(
...
)
}
}
}
that your Activity/Fragment could then observe for changes
viewModel.state.observe(.. { state ->
// DO SOMETHING
})
P.S. The tutorial also mentions that because of how Dao's work, you might be getting updates for even the slightest of changes, but that you can use the distinctUntilChanged() Flow extension function to get more specific results.
I recently ran into discussion about usage of Subject, like this one here: https://github.com/JakeWharton/RxRelay/issues/7
I see a lot of people saying that Subject should be avoided and some people even say any usage of Subject is inherently a bad practice. While I agree on the theoretical level that Subject can be and should be avoided, I can hardly get rid of subjects in real practices. It seems impractical, or even impossible to do so.
Imagine a simple theoretical weather app that has just two things:
a view that displays current weather information
a refresh button which re-fetch the weather information from the server.
(Let's assume for simplicity that the app does not show the data at initial launch, but waits for the users to press refresh button at least once.)
Then you can think of a view model design like this:
ViewModel
interface IWeatherViewModel {
// Provides weather data
Flowable<WeatherData> getWeatherDataToDisplay();
// Lets view to refresh
void refresh();
}
If I use Subject then IWeatherViewModel can be implemented like this:
class WeatherViewModel implements IWeatherViewModel {
private final BehaviorProcessor<WeatherData> weatherData = BehaviorProcessor.create();
private final PublishProcessor<Boolean> eventRefresh = PublishProcessor.create();
WeatherViewModel() {
eventRefresh
.flatMapSingle(x -> getWeatherData())
.subscribe(weatherData);
}
// Provides weather data
public Flowable<WeatherData> getWeatherDataToDisplay() {
weatherData.hide();
}
// Lets view to refresh
public void refresh() {
eventRefresh.onNext(true);
}
private Single<WeatherData> getWeatherData() {
... // omitted for simplicity
}
}
The idea is to have a PublishProcessor that emits refresh event whenever refresh() is called which is then propagated to a BehaviorSubject. All subscribers that observe getWeatherDataToDisplay() will be notified once getWeatherData() is successful.
However I find it difficult to implement the same thing without Subject.
The app needs to propagate refresh() call to stream. I might be able to replace PublishProcessor using Flowable.create() but it doesn't look clean at all, the best I could do is:
private FlowableEmitter emitter;
private final Flowable<Boolean> eventRefresh = Flowable.create(emitter -> {
this.emitter = emitter;
}, BackpressureStrategy.BUFFER);
public void refresh() {
emitter.onNext(true);
}
Now suddenly I have to have a new instance variable that I cannot make final..
Also I am not able to find any operator that can effectively replace BehaviorProcessor, nor any hot observable that emits the latest item immediately on subscription. This behavior is necessary because the view should be able to detach and re-attach seamlessly, just like LiveData.
If you see any improvement that can be made, or have a different approach to the problem, please share your thougts.
I'm having trouble understanding the problem in this scenario.
I have a class used for Analytics Tracking, lets call it FlurryTracker,
it has 2 methods StartTrackingScreen(ScreenName) and StopTrackingScreen().
Now if I have a static var called screenName and each time start tracking screen is called screenName is reassigned.
startTrackingScreen(activity: Activity, screen: DhTracker.Screen<T>) {
screenName = screen.getName()
val lastScreen = Singleton.getLastScreen()
//If last screen is not same as current screen
FlurryAgent.logEvent(screenName, true)
}
}
override fun stopTrackingScreen() {
//New screen will start tracking before lastScreen tracking is stopped.
if (enabled) {
FlurryAgent.endTimedEvent(Singleton.getLastScreen()?.getName())
}
}
companion object{
lateinit var screenName : String
}
These methods are called in onStart() and onStop() in the app itself.
So with that being said, we are only tracking 1 screen at a time because when the user transitions to a new screen, onStop() and onStart() will be called.
So even though screenName is static, every time the lifecycle methods are called, that static var is being reassigned. Since a phone can't have 2 activites running at the same time, there will only be 1 instance of my tracker active at a time.
I don't really see the problem with using a static here, although I know best practices say that screenName should be created with every new instance. Am I looking at this the wrong way?
You can do that.
The two main patterns for something like this are static variables & methods or a singleton (That is often static so you can use it from different paths without passing it around). Both of these approaches are functionally identical.
The negatives for the static class are:
Difficult to test due to the fact that you have to replace the static method
Difficult to create a second instance
Difficult to pass around if you decide you want to (Some people like to know what classes are used by a given path for testing purposes)
These aren't that bad, you can live with them--however none of these issues exist if you use a singleton. You can easily pass it around, change it's behavior, convert it to use injection instead of the singleton pattern, …
So I can't really come up with a reason to ever use the static approach, there aren't any advantages.