X++ in D365 Finance and Operations: Observer and display methods

If you find yourself needing to trigger an independent display method within a form class upon the occurrence of a variable change, data source modification or event, employing the X++ observer can be of help.

There are three distinct methods to utilize the X++ observer:

One approach is to employ the observe() method of a datasource object. With this method, whenever a change occurs within a datasource, any associated code encompassing the <datasource>.observe() call will be executed.

//Example 1 – FormDataSource observe
[ExtensionOf(formStr(SimpleForm))]
final class SimpleForm_Form_Extension
{
    public display boolean displayCallMyMethodByFormDataSourceObserver()
    {
        myFormDataSource_ds.observe();   //Called FormDataSource observer()
        return isThisHelpful();
    }
}

You can define a variable with the [FormObservable] attribute. Whenever this variable undergoes a change, the corresponding code that utilizes it will be executed.

//Example 2 – FormObservable attribute
[ExtensionOf(formStr(SimpleForm))]
final class SimpleForm_Form_Extension
{
    [FormObservable]
    private int counter;

    public void someMethod();
    {
        //Code ...
        counter = 0; //<--- Changing variable with FormObservable attribute
        //Code ...

    }
    public display int displayCounter()
    {
        return counter; //Called because of FormObservable attribute
    }
}

Another option is to utilize the FormObservableLink class for creating a FormObservableLink object. With the markChanged() method, you can initiate a change, and by employing observe(), you can capture the change event.

//Example 3 – FormObservableLink calls
[ExtensionOf(formStr(SimpleForm))]
final class SimpleForm_Form_Extension
{
    private int counter = 0;

    FormObservableLink fOL = new FormObservableLink(); //1.  Create a instance of FormObservableLink

    public void someMethod();
    {
        //Code ...
        counter = 0;
        fOL.markChanged(); //2. Call change somwhere
        //Code ...

    }
    public display int displayCounter()
    {
        fOL.observe(); //3. Called through markChanged();
        return counter; 
    }
}

May this aid you in your continued journey within the realm of Microsoft D365 F&O development.

Another useful posts about this topic:
Blog on Microsoft Dynamics AX/ D365: Observer x++ D365FO (sangeethwiki.blogspot.com)
FormObservableLink works in data source extensions – Goshoom.NET Dev Blog