티스토리 뷰
We are using static items for hero list. What do we do if I want to load data from a service. We are going to use same data but we will use data loader instead of hard coded data.
Let's initialise hero data first. We need to provide @OnCreateInitialState annotate function to do this in HeroesComponentSpec.
@GroupSectionSpec
object HeroesComponentSpec {
@OnCreateInitialState
fun onCreateInitialState(c: SectionContext) {
//TODO. Data initialisation
}
...
}
@OnCreateInitialState must have SectionContext as its first parameter. And then we can provide more parameters if we need and they should be one of @Prop or StateValue<T>. They are basically similar to hold data of the component. But @Prop doesn't not provide any way to update data. StateValue can update state of component.
@OnCreateInitialState
fun onCreateInitialState(c: SectionContext, heroes: StateValue<List<Hero>>) {
heroes.set(DataLoader.HEROES.take(4))
}
I setup HeroesComponentSpec to have 4 heroes initially. Now let's compile and we will have an error:
e: /.../HeroesComponentSpec.java:13: error: Not a valid parameter, should be one of the following: @Prop T somePropName. @TreeProp T someTreePropName. StateValue<T> stateName, where a state param with type T and name stateName is declared elsewhere in the spec. @InjectProp T someInjectPropName.
com.facebook.litho.StateValue<java.util.List<com.mpark.android.marblecharacters.Hero>> heroes) {
We should have heroes parameter in onCreateChildren function as well once we define heroes parameter onCreateInitialState. Let's add it to onCreateChildren.
internal fun onCreateChildren(c: SectionContext, @State heroes: List<Hero>): Children {
...
}
We should use @State in onCreateChildren because heores should be readonly in the function. And we just use it in onCreateChildren instead of hardcoding it.
@OnCreateChildren
internal fun onCreateChildren(c: SectionContext, @State heroes: List<Hero>): Children {
val builder: Children.Builder = Children.create()
val sectionList: List<SingleComponentSection> = heroes.map { hero ->
SingleComponentSection.create(c)
.key(hero.name)
.component(
...
)
.build()
}
return builder
.child(sectionList)
.build()
}

'Android > Litho' 카테고리의 다른 글
| 8. Stop Loading (0) | 2019.11.10 |
|---|---|
| 5. HeroItemSpec (0) | 2019.11.10 |
| 4. GroupSection Spec LifeCycle (0) | 2019.11.09 |
| 3. Sample Application - HeroesComponentSpec (0) | 2019.11.09 |
| 2. Sample Application - Intialisation (0) | 2019.11.09 |
