Supporting a Serialization Format
View Tree Loaders, View Builders and Nodes
The process of loading a view tree from a serialized format contains
three components:
1. View Tree Loaders: A View Tree Loader traverses a tree of nodes of
key-value pairs that represent a view. At each node, it calls a
View Builder that builds the view from the given key-value pairs.
2. View Builders: View Builders are responsible for building a single
view from key-value pairs.
3. Nodes: A node is responsible for parsing the key-value pairs from
a string. There are two types of nodes, a layout node that represents
a layout view and a normal node that represents a non-layout view. In
the tree that the View Tree Loader operates on, all non-leaf nodes are
layout nodes while leaf nodes are just normal nodes.
As we can, View Tree Loaders and View Builders are oblivious to the serialization format, they only operate on key-value pairs. As a result, if we want to support a new serialization format, all what we have to do is add the corresponding Node objects.
In this example, we will add support for loading views from the YAML format.
Add YAML parser
In your common code, declare the class that is responsible for parsing the YAML and provide its implementation on each platform.
expect class YamlParser() {
fun parse(yamlString: String): Map<String, Any>
}
Add the YAML nodes
import view.core.loaders.viewTree.nodes.Node
import view.core.loaders.viewTree.nodes.LayoutNode
class YamlNode(yamlString: String): Node() {
override var content = YamlParser().parse(yamlString)
}
class YamlLayoutNode(yamlString: String): LayoutNode() {
override var content = YamlParser().parse(yamlString)
}
You can use the nodes as follows:
import view.core.loaders.viewTree.treeLoaders.SerializedViewTreeLoader
val yamlString = "....."
val rootNode = YamlLayoutNode(yamlString)
val treeLoader = SerializedViewTreeLoader(rootNode)
val viewTree = treeLoader.loadViewTree()
Optional: Add a ViewTreeLoader
Optionally, you can encapsulate the usage of nodes by creating a new tree loader.
import view.core.loaders.viewTree.treeLoaders.SerializedViewTreeLoader
class YAMLTreeLoader(yamlString: String): SerializedViewTreeLoader(YamlLayoutNode(yamlString))
You can use the loader as follows:
val yamlString = "....."
val treeLoader = YAMLTreeLoader(yamlString)
val viewTree = treeLoader.loadViewTree()
As we can see, it is very simple to support a new serialization format.