2022年9月17日土曜日

derivedStateOf の効果を LayoutInspector の composition count で確認する

derivedStateOf を使っていない、よくないコード
  1. val state = rememberLazyListState()  
  2.   
  3. // TODO derivedStateOf を使う  
  4. val showScrollToTopButton= state.firstVisibleItemIndex > 0  
  5.   
  6. LazyColumn(  
  7.     state = state,  
  8.     modifier = Modifier.fillMaxSize()  
  9. ) {  
  10.     ...  
  11. }  
  12.   
  13. if (showScrollToTopButton) {  
  14.     Button(  
  15.         onClick = {  
  16.             ...  
  17.         },  
  18.         ...  
  19.     ) {  
  20.         Text("scroll to top")  
  21.     }  
  22. }  
LayoutInspector で Button が表示されたあともスクロールのたびに recompose が走っているので Button の skip count が増えていっています。
  1. val showScrollToTopButton by remember {  
  2.     derivedStateOf { state.firstVisibleItemIndex > 0 }  
  3. }  
に変えると、スクロールのたびに recompose が走っていたのがなくなり、Button の skip count が増えなくなりました。



0 件のコメント:

コメントを投稿