Oninit Custom Widget

Creating a custom widget with onInit.

Currently in Beagle, the Container and ListView components have the behavior of executing a list of actions as soon as they are rendered. For this, they expose the onInit property, which receives the list of actions that will be triggered.

To create a custom widget with the behavior of triggering a list of actions as soon as it is rendered, Beagle provides an easy way to do it using the default delegate by implementing the OnInitiableComponent interface.

With the customizable widget created, add the OninitiableComponent interface:

@RegisterWidget
class CustomInitiableWidget(
    val name: String,
    val phone: String,
    val age: Int
): WidgetView(), OnInitiableComponent {
    override fun buildView(rootView: RootView): View {
        TODO("Not yet implemented")
    }
}

Step 2: Implement onInit property

After adding the OnInitiableComponent interface to the widget, override the onInit property:

@RegisterWidget
class CustomInitiableWidget(
    val name: String,
    val phone: String,
    val age: Int,
    override val onInit: List<Action>?
): WidgetView(), OnInitiableComponent {
    override fun buildView(rootView: RootView): View {
        TODO("Not yet implemented")
    }
}

Step 3: Delegate implementation

In addition to the onInit property, the OnInitiableComponent interface needs the implementation of the handleOnInit and markToRerunOnInit methods. To facilitate and maintain the component’s default behavior, Beagle already provides an implementation and it is recommended to use it by delegating to OnInitiableComponentImpl:

@RegisterWidget
class CustomInitiableWidget(
    val name: String,
    val phone: String,
    val age: Int,
    override val onInit: List<Action>?
): WidgetView(), OnInitiableComponent by OnInitiableComponentImpl(onInit) {
    override fun buildView(rootView: RootView): View {
        TODO("Not yet implemented")
    }
}

Step 4: Run handleOnInit

Finally, with all the configuration done in the widget, only the execution of the handleOnInit method is missing so that the list of onInit actions can be executed as soon as the view is rendered:

@RegisterWidget
class CustomInitiableWidget(
    val name: String,
    val phone: String,
    val age: Int,
    override val onInit: List<Action>?
): WidgetView(), OnInitiableComponent by OnInitiableComponentImpl(onInit) {
    override fun buildView(rootView: RootView): View {
        handleOnInit(rootView, view)
    }
}

It’s done! Your component now performs a list of actions whenever it is rendered!


Last modified September 17, 2021: Reviewed Android section (#773) (e4c75e98)