Diagram Groups are not properly retaining its expand/collapse state

In my application, I wanted a option to collapse and expand all the available groups with a click of a button. I am invoking the following toggleGroups method to exapand or collapse all groups.

function toggleGroups(toggle){
      myDiagram.commit((diag) =>{
        diag.nodes.each((g) => {
          if (g instanceof go.Group){
            g.isSubGraphExpanded = toggle;
          } 
        })
      });
}

I have created a group and that has multiple inner groups inside.

Expand all and collapse all groups working fine using toggleGroups(flag) method. toggleGroups(false) will collapse all the groups.

Issue with method:
Now I tried to expand only the outer most group (myGroup3) using the little plus(+) button and noticed some issue here.

Expected behaviour:
If I tried to expand the outer group i.e., myGroup3, only myGroup3 should get expand and remaining groups(myGroup1, myGroup2 and myGroup4) should remain collapsed.

Current behaviour:
Along with myGroup3 all its inner groups are getting expanded. This is not a expected behavior.

Note: This scenario is working fine, if I collapse all the groups manually using (-) button not with toggleGroups(false) method.

Please suggest me a way to fix.

Group.expandSubGraph depends on Group.wasSubGraphExpanded to decide whether or not to expand each nested group.
Group | GoJS API
Group | GoJS API
Group | GoJS API

So it really depends on the order in which you set Group.isSubGraphExpanded to false.

Or else you can set Group.wasSubGraphExpanded as you wish after having collapsed everything.

Or perhaps you just want to collapse all groups by doing this instead:

myDiagram.commit(diag => {
  diag.findTopLevelGroups().each(grp => grp.isSubGraphExpanded = false);
});

Then doing this will restore the expanded states of nested groups:

myDiagram.commit(diag => {
  diag.findTopLevelGroups().each(grp => grp.isSubGraphExpanded = true);
});

Thanks @walter for your speedy response.
I have tested with your solution. The following syntax is not serving my purpose. It just expands/collapse the top level group, not all the nested groups.
I want all the groups to be expand/collapse and also individual group expand/collapse action should not affect.

myDiagram.commit(diag => {
  diag.findTopLevelGroups().each(grp => grp.isSubGraphExpanded = false);
});

If it doesn’t do what you want, try one of my other suggestions.

Following syntax worked for me. Thanks for your help @walter .

 myDiagram.commit((diag) =>
        diag.nodes.each((g) => {
          if (g instanceof go.Group){
            g.isSubGraphExpanded = toggle;
            g.wasSubGraphExpanded = toggle
          } 
        })
      );