Component Lifecycle

When component is first displayed on the page, i.e. the Xamarin Forms widget is added to the page visual tree ReactorUI calls the method OnMounted().

Before component a component is removed from the page visual tree ReactorUI calls the OnWillUnmount() method.

OnMounted() is the ideal point to initialize the component for example calling web services or query local database to get the require information to render the component in the Render() method.

For example in this code we'll show an activity indicator while component is loading:

public class BusyPageState : IState
{
    public bool IsBusy { get; set; }
}

public class BusyPageComponent : RxComponent<BusyPageState>
{
    protected override void OnMounted()
    {
        SetState(_ => _.IsBusy = true);

        //OnMounted is called on UI Thread, move the slow code to a background thread
        Task.Run(async () =>
        {
            //Simulate lenghty work
            await Task.Delay(3000);

            SetState(_ => _.IsBusy = false);
        });

        base.OnMounted();
    }

    public override VisualNode Render()
    {
        return new RxContentPage()
        {
            new RxActivityIndicator()
                .VCenter()
                .HCenter()
                .IsRunning(State.IsBusy)
        };
    }
}

and this is the resulting app:

NOTE: Do not use constructors to pass parameters to the component but public properties instead (take a look at the Custom Components documentation page.

Last updated