CoroutineScope: ์ฝ๋ฃจํด์ด ์คํ๋๋ ๋ฒ์, ์๋ช ์ฃผ๊ธฐ ๊ด๋ฆฌ์ ์ค์
์ผ์ ์ค๋จ ํจ์: ์ค๋จ ๊ฐ๋ฅํ ํจ์ -> delay(), withContext() ๋ฑ์ด ์์
๋์คํจ์ฒ : ์ฝ๋ฃจํด์ด ์คํ๋ ์ค๋ ๋๋ฅผ ์ ์ (Main, IO, Default ๋ฑ)
์ฝ๋ฃจํด ๋น๋: launch, async, withContext ๋ฑ์ด ์์ผ๋ฉฐ ์ฝ๋ฃจํด์ ์์ฑํ ๋ ์ฌ์ฉ
@Composable
fun CoroutineExample() {
val scope = rememberCoroutineScope()
Button(onClick = {
scope.launch {
delay(1000)
println("1์ด ํ ์คํ๋จ")
}
}) {
Text("์คํ")
}
}
=>LaunchedEffect๋ ์ปดํฌ์ ๋ธ์ด ์ฒ์ ์ปดํฌ์ฆ๋ ๋ ํน์ ์์
์ ์๋์ผ๋ก ์คํํ๊ณ ์ถ์ ๋ ์ฌ์ฉ
val channel = Channel<Int>()
scope.launch {
channel.send(1)
}
scope.launch {
val received = channel.receive()
println(received)
}
- Compose์์๋ ๋ฆฌ์คํธ๋ ๊ทธ๋ฆฌ๋ UI๋ฅผ ๊ตฌ์ฑํ ๋ ์ฑ๋ฅ๊ณผ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๊ณ ๋ คํ์ฌ Lazy ์ปดํฌ์ ๋ธ์ ํ์ฉ
- Lazy ์ปดํฌ์ ๋ธ์ ๋ณด์ด๋ ํญ๋ชฉ๋ง ๋ ๋๋งํ์ฌ ์คํฌ๋กค์ด ๋ง์ UI์์๋ ๋ฐ์ด๋ ์ฑ๋ฅ์ ์ ๊ณต
LazyColumn {
items(list) { item ->
Text(text = item.name)
}
}
LazyRow: ๊ฐ๋ก ์คํฌ๋กค์ด ๊ฐ๋ฅํ ๋ฆฌ์คํธ
LazyVerticalGrid: ๊ฒฉ์ํ ๋ ์ด์์์ผ๋ก ์ํ ๋ฆฌ์คํธ, ๊ฐค๋ฌ๋ฆฌ ๋ฑ์ ์ ํฉ
LazyRow {
items(items) { item ->
Card(Modifier.padding(8.dp)) {
Text(item.title)
}
}
}
LazyVerticalGrid(columns = GridCells.Fixed(2)) {
items(items) { item ->
GridItem(item)
}
}
val listState = rememberLazyListState()
LazyColumn(state = listState) { ... }
LaunchedEffect(Unit) {
listState.animateScrollToItem(10)
}
LazyColumn {
stickyHeader {
Text("ํค๋", modifier = Modifier.background(Color.LightGray))
}
items(list) {
Text(it.title)
}
}
์คํฌ๋กค ์์น์ ๋ฐ์ํ๊ธฐ
val isScrolled = remember {
derivedStateOf {
listState.firstVisibleItemIndex > 2
}
}
val items = listOf("์ฒซ ๋ฒ์งธ", "๋ ๋ฒ์งธ", "์ธ ๋ฒ์งธ")
Column {
items.forEach {
Text(it, modifier = Modifier.padding(8.dp))
}
}
val scrollState = rememberScrollState()
Column(modifier = Modifier.verticalScroll(scrollState)) {
for (i in 1..50) {
Text("์์ดํ
$i", modifier = Modifier.padding(8.dp))
}
}
assets/data.xml์ ์ํ ๋ฐ์ดํฐ๋ฅผ ์ถ๊ฐํ๊ณ ํ์ฑ
๋ชจ๋ธ ํด๋์ค ์์ฑ: data class Item(val name: String, val imageUrl: String)
@Composable
fun ItemCell(item: Item) {
Row(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
Image(...)
Column(modifier = Modifier.padding(start = 8.dp)) {
Text(item.name, fontWeight = FontWeight.Bold)
}
}
}
LazyColumn {
items(items) { item ->
ItemCell(item)
}
}
ItemCell(item = item, onClick = { navigateToDetail(item) })
val grouped = items.groupBy { it.category }
LazyColumn {
grouped.forEach { (category, itemList) ->
stickyHeader {
Text(text = category, modifier = Modifier.background(Color.Gray).padding(8.dp))
}
items(itemList) {
ItemCell(it)
}
}
}
val scope = rememberCoroutineScope()
val listState = rememberLazyListState()
Button(onClick = {
scope.launch {
listState.animateScrollToItem(0)
}
}) {
Text("๋งจ ์๋ก")
}