c# - Working with Trees in Rx.NET / ReactiveUI -
how observe property changes on sublevel of tree?
consider example class treenode
properties name
, childnodes
. how observe name
changes on sublevel of treenode
?
the usage might this:
rootnode.flattentreetoobservable(x => x.childnodes) .whenanyvalue(x => x.name) .subscribe(...)
treenode example:
// nuget: install-package reactiveui // in case of splat version issue: install-package splat -version 1.6.2 using reactiveui; public class treenode: reactiveobject { public string name { { return this._name; } set { this.raiseandsetifchanged(ref this._name, value); } } private string _name = ""; public reactivelist<treenode> childnodes { { return this._childnodes; } set { this.raiseandsetifchanged(ref this._childnodes, value); } } private reactivelist<treenode> _childnodes = new reactivelist<treenode>(); }
i couldn't code run - ended dll versioning issue wrote basic class uses same structure yours work:
public class treenode { public string name { get; set; } public subject<treenode> childnodes { get; } = new subject<treenode>(); }
i added following method:
public iobservable<treenode> flattentreetoobservable() { return this.childnodes .selectmany(cn => cn.flattentreetoobservable()) .startwith(this); }
now when run test code:
var root = new treenode() { name = "r" }; root.flattentreetoobservable().subscribe(tn => console.writeline(tn.name)); var a1 = new treenode() { name = "a1" }; root.childnodes.onnext(a1); var b11 = new treenode() { name = "b11" }; a1.childnodes.onnext(b11); var b12 = new treenode() { name = "b12" }; a1.childnodes.onnext(b12); var a2 = new treenode() { name = "a2" }; root.childnodes.onnext(a2); var b21 = new treenode() { name = "b21" }; a2.childnodes.onnext(b21); var b22 = new treenode() { name = "b22" }; a2.childnodes.onnext(b22);
i output:
r a1 b11 b12 a2 b21 b22
Comments
Post a Comment