Android's viewDidLoad and viewDidAppear equivalent - iphone

Does Android have an equivalent to Cocoa's viewDidLoad and viewDidAppear functions?
If not, then how would I go about performing an action when a View appears? My app is a tabbed application, in which one of the tabs is a list of forum topics. I would like the topic list to be refreshed every time the view appears. Is such a thing possible in Android?

The Activity class has onCreate and onResume methods that are pretty analagous to viewDidLoad and viewDidAppear.
Activity.onResume
EDIT
To add to this, since some have mentioned in the comments that the view tree is not yet fully available during these callbacks, there is the ViewTreeObserver that you can listen to if you need first access to the view hierarchy. Here is a sample of how you can use the ViewTreeObserver to achieve this.
View someView = findViewById(R.id.someView);
final ViewTreeObserver obs = someView.getViewTreeObserver();
obs.addOnPreDrawListener(new OnPreDrawListener() {
public boolean onPreDraw() {
obs.removeOnPreDrawListener(this);
doMyCustomLogic();
return true;
}
});

onResume() is more like viewCouldAppear. :) public void onWindowFocusChanged(boolean) is the closest to viewDidAppear. At this point within the activity lifecycle you may ask the view about its size.

From my limited, nascent understanding of Android, you implement viewDidLoad type functionality in the onCreate method of your Activity:
onCreate(Bundle) is where you
initialize your activity. Most
importantly, here you will usually
call setContentView(int) with a layout
resource defining your UI, and using
findViewById(int) to retrieve the
widgets in that UI that you need to
interact with programmatically.
The equivalent for viewDidAppear is closer to the onResume method:
Called after
onRestoreInstanceState(Bundle),
onRestart(), or onPause(), for your
activity to start interacting with the
user. This is a good place to begin
animations, open exclusive-access
devices (such as the camera), etc.

Related

How to update a value after it is loaded inViewDidLoad in another file (Swift)?

I have created all my views programatically and to the UIView I have created an extension. This extension is present in a different file called App+Extensions.swift
extension UIView {
func setupParentView() -> UIView {
//...
}
}
The setupParentView() gives me a view with my navbar and background colour. As the design is same everywhere I have used this function. This function is called everywhere in viewDidLoad. So, now in this function the navabar consists of points which need to updated every time the user has purchased/spent it.
So, now as this method is only called in viewDidLoad the function is not called again and the point value do not change in the navigation bar. So, how can I update the point value every time it is changed? I thought of using Combine, but this app will be available for iOS 12 users as well, and I am not using RxSwift, so any help?
Well ViewDidLoad won't get refreshed because your view is now in the stack hierarchy. Some override methods that do get called which have a relation to the view are viewWillAppear, viewDidDissapear, and viewDidAppear.
If your view is going back in forth and the point button needs to be updated everytime your view re-appears consider putting the "refresh" point number in one of the above methods.
Note if your sending info back and forth between two views its also best maybe implement a delegation pattern or an observer.
Use notifications.
In other words, have points be a property of a global object that lives off in "data space" as a singleton. Now just use a property observer so that whenever anyone changes that object's points property, it emits a notification through the NotificationCenter.
That way, any view or view controller that needs to update whenever the points property changes just has to register for that notification when it comes into existence.
[Basically, this is the mechanism, or one of the mechanisms, that you would be replacing or even using directly if you were using Combine or RxSwift.]
Create a custom view called NavBarView
This NavBarView has a property called point
var point = 0 { didSet { updateView() } }
You want to avoid singleton, single view object, so that not everything is coupled together.
You don't need RxSwift or notification to do this.

How to Dispose a ViewModel after Popping a page with Xamarin.Forms?

What I would like to do is unsubscribe from events at the moment the ViewModel is no longer needed. I tried implementing IDisposable but nobody calls Dispose(), not Xamarin.Forms nor Prism.Forms.
We have an app created with Xamarin.Forms. We use Prism.Forms to do MVVM. When navigating to a new page (push on stack) Prism.Forms wires the ViewModel to the Page. When navigating back (pop from stack) the ViewModel gets GarbageCollected after a while.
The problem is however that at a point in time we have a couple of the same type of ViewModels with subscriptions to events that are not bound to a View. When the events fire all these ViewModels start doing their thing. So I am looking for a way to unsubscribe at the moment the subscription is no longer needed.
Does anyone have a solution?
You can make sure the Dispose() is called in the OnDisappearing() event of the View, if you want to ensure that ViewModel is not present anymore in the memory than the view.
It is better if you care only about subscribe and unsubscribe of events, then to do it in the OnAppearing() and OnDisappearing(). In that case you will be sure of no event handlers been present on the viewmodel once view is not visible.
Implement IDestructible or INavigationAware
(or both as in BaseViewModelsample from Prism).
Depending on your object lifecycle :
Implement your disposal code in the Destroy method of IDestructible interface.
Implement your disappearing/appearing code in the OnNavigatedFrom/OnNavigatedTo methods on INavigationAware interface.
Bonus:
IDestructible can be implemented also by the View (and it will called accordingly by Prism when the view is destroyed).
Note:
While the solution above using OnAppearing/OnDisappearing works, it induces that ViewModel will depends on a call from View for managing its lifecycle (not clean). Moreover these methods don't exist on ContentView.

Reload application in SAPUI5

Is there any way by which we can reload the whole SAPUI5 application?
When a SAPUI5 app is called, onInit() function is called and we are initializing some settings for view here. Say if some change (like selection of a checkbox in master view) requires the whole application to be reset, can we reload the application and call onInit() function again to correct our initial settings? Is there any trigger mechanism by which we can call onInit() function explicitly?
Thank you in advance for your suggestions.
Regards,
Raja
If you have the need to reload or reset your application, then I would think your app suffers from a major design flaw... This is definitely something I would look into first if I were you!
However, to answer your question, why not move the initialization code into its own function, and call that function from the onInit() event handler and whenever you need to reset your app?
I suggest you to use some kind of intercommunication (e.g.: EventBus) between your Controller instances, from the master view notify your Controllers to rerun initialization logic like follows:
move you initialization logic to separate functions on each Controller and call this method upon onInit
in onInit subscribe to reinitialize event
in you master view add a listener function to the mentioned checkbox selection event, and publish the reinitialize event to notify your Controllers to reinitialize
Controller.js:
function onInit() {
this._initialize();
EventBus.subscribe('reinitialize', this._initialize);
}
funcion _initialize() {
// init logic
}
MasterController.js:
function onSelectionChange() {
EventBus.publish('reinitialize');
}
Sometimes you cannot directly use the window global variable in sapui5.
Refer to this page:
https://help.sap.com/viewer/825270ffffe74d9f988a0f0066ad59f0/CF/en-US/7d0dba71a2cb45ebb1959daba904ca99.html?q=location%20reload
var myLocation = location;
myLocation.reload();

Who should create view model instances in MvvmCross

Just to make it clear: I know MvvmCross is very flexible about where and how view models can be created. My question is more about proper separation of concerns, to simplify design of complex cross-platform applications.
Consider we have an app with customer list and customer details. On iPad and Surface the list and details are shown on the same page, but on smaller devices customer list and details for a selected customer are split between separate pages. So we have a PCL with CustomerListViewModel and CustomerDetailsViewModel. Now how should we manage view model lifetime from within the portable class library?
I originally did it using code in CustomerListViewModel implementation that looks like this:
public ICommand SelectCustomerCommand
{
get { return new MvxCommand(SelectCustomer); }
}
public void SelectCustomer()
{
if (formFactor == FormFactor.Phone)
{
ShowViewModel<CustomerDetailsViewModel>(new CustomerDetailsViewModel.NavObject(this.SelectedCustomer));
}
else
{
this.CustomerDetails = new CustomerDetailsViewModel(this.SelectedCustomer);
}
}
What is essential here is that we either call ShowViewModel that in turns asks a presenter to construct a CustomerDetailsViewModel object and render it in a new page or explicitly create an instance of CustomerDetailsViewModel and bind it to CustomerDetails.
After having seen episodes 32 and 42 of N+1 MvvmCross video series I am not quire sure this is the right way to do it. Of course it works, but should a view model care about instantiation details of other view model?
My second thought was to refactor this code and put this logic into a presenter, so I can simply write in CustomerListViewModel implementation:
public void SelectCustomer()
{
ShowViewModel<CustomerDetailsViewModel>(new CustomerDetailsViewModel.NavObject(this.SelectedCustomer));
}
... and presenter will do the rest inside the code triggered by ShowViewModel call. However, in the episode 42 it's shown how to control view model lifetime right from the associated view:
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
VisibleViewModel.IsVisible(false);
if (e.NavigationMode == NavigationMode.Back)
KillableViewModel.KillMe();
}
But if a view model lifetime is controlled by a presenter, shouldn't we try to place KillMe call inside presenter's logic? I know so small piece of code doesn't make much difference but couldn't this be an advantage to put it in presenter's class and reduce code-behind?
Definitely the ViewModel should not handle anything in regards to view (screen).
One quick idea I have is use a custom presenter which is able to create views based on the ShowViewModel<> requests.
The custom presenter is a view responsibility so you can test for screen orientation.
http://slodge.blogspot.co.uk/2013/06/presenter-roundup.html
For the second part of this question:
But if a view model lifetime is controlled by a presenter, shouldn't we try to place KillMe call inside presenter's logic? I know so small piece of code doesn't make much difference but couldn't this be an advantage to put it in presenter's class and reduce code-behind?
Currently view model presentation is orchestrated by the presenter - it gets ViewModelRequest objects and decides what to do with them.
However, it doesn't normally create the ViewModels - instead:
the presenter normally creates/shows a View
then the View creates (or locates) a ViewModel as part of the OnCreate, ViewDidLoad or OnNavigatedTo handling.
And so I don't think a ViewModel's lifetime is normally "controlled by a presenter" - instead I think a ViewModel is a "Model for a View" - so it's lifetime is "controlled by its view".
For the occasions where you need shutdown/dispose/killMe logic in your ViewModel, if you wanted to move that logic back inside the presenter - or into some other object - then you definitely could do so if you wanted to - it's your app and the app is king.
However, in these cases I suspect you would need the presenter to get some kind of notification from the View - as often the presenter doesn't know when Views are removed (when a modal is dismissed, when a Back button is pressed, when Android clears up stack views to save memory, etc).
As another way of thinking about this, if the presenter were renamed as INavigationService then what roles do you want that INavigationService to own within your app?

Delegation, some example of code? How object delegate to other

I would like to gain a better understanding about the delegation. Can somebody please paste a good code sample of delegation and explain how it works?
There is a pretty good example at: http://en.wikipedia.org/wiki/Delegation_pattern#Objective-C_example
In this example, MyCoolAppController creates and object of type TCScrollView, and sets the "delegate" property of the TCScrollView to self. This means that when the TCScrollView calls
[delegate scrollView:self shouldScrollToPoint:to]
it is asking the MyCoolAppController (the delegate of the TCScrollView) to perform some calculations and see if it is ok to scroll. You can say "MyCoolAppController is the delegate of TCScrollView" to describe this; TCScrollView asks MyCoolAppController to do some work on its behalf.
Do you mean .NET or Java or some other language delegate?
A delegate in .NET parlance is nothing more than a function pointer, or in other words a variable that points to a block of executable code. They can be used in may ways. One way is to use them in the context of events. Lets say you have an ASP.NET page and you are using the MVP (Model View Presenter pattern on that page). You want your presenter to be notified of the click event of the save button on the view. You can define an event on the views interface, but in order to subscribe to that event and to take action on it you need to register a method that gets fired when the event is raised. For example:
public class ClassThatRegistersForEvent
{
public void InitializeView(IView view)
{
view.SaveButtonClickedEvent += delegate{
// do stuff in here when the event is raised
}
}
}
public interface IView
{
event System.EventHandler SaveButtonClickedEvent;
}
Here's an answer I wrote explaining delegation: https://stackoverflow.com/questions/1089737#1090170
A delegate is a way to respond to events. In other languages you would probably do this by subclassing. For example, say you have a table view. You could subclass the tableview and override the tableView:didSelectRowAtIndexPath: method, but that would get messy and create an unnecessary subclass (along with the fact that its not reusable) Instead, you create a TableViewDelegate class and tell your table view about it (tableView.delegate). This way, the method will automatically get called when something happens. This is a really clean solution to event-handling.
After you write a few apps that involve delegates (table views are the big ones), you'll get the hang of it.