https://kotlinlang.org logo
t

takahirom

11/10/2020, 1:26 AM
I have a question about Stateless composables. https://developer.android.com/jetpack/compose/state#stateless-composables Suppose you have a tab under HomeScreen and a list under it. HomeScreen → Article Tab → Favorite Tab → About Tab ... If you make HomeScreen Stateless, you will need to take a lot of arguments. What do you think should be done in such a case? Is it better not to make Composable like HomeScreen Stateless?
Copy code
/*
 * stateless
 */
fun HomeScreen(val currentTab, val articleList...., onFavorite:()->Unit) {
}
j

jim

11/10/2020, 1:28 AM
Copy code
class HomeScreenState {
  val articleTabState = ...
  val favoriteTabState = ...
  val aboutTabState = ...
}

@Composable fun HomeScreen(homeState: HomeScreenState) { ... }
When you hoist state objects, you can have state objects that contain references to other state objects, just like you would do if you called a normal function that needed to pass data into another function.
t

takahirom

11/10/2020, 1:50 AM
Thank you. If there are HomeViewModel and ArticleViewModel, do you mean that you need a mechanism to convert to that State?
j

jim

11/10/2020, 2:57 AM
Yeah, ideally your composables should probably be completely independent of ViewModel, since ViewModel is very much an Android concept. Having composables that are independent of Android will make a whole bunch of things easier (unit testing, Compose Desktop, etc)
That is to say, you don't want the data class definitions accepted by your composables to be tightly coupled to your application.
t

takahirom

11/10/2020, 7:02 AM
Thank you so much for your kindness! I was trying to force the value and event listener to pass. Should I think of it as follows? State hoisting(to pass value and event listener) as much as possible. However, if there are too many arguments or the arguments know too much detail, create a grouped object without passing ViewModel(Implemented class) or pass interface.
👍 1
w

wisdom

11/10/2020, 8:06 AM
@jim are we still going to write code to save state in Jetpackcompose, since it's independent of Viewmodel?