Use of ViewModel, Flow, Hilt and Coil in Jetpack Compose

Posted by jmboblee on Fri, 24 Dec 2021 19:47:38 +0100

Compose can be used with multiple Jetpack components

Compose can cooperate with the development of multiple Jetpack components to improve development efficiency

Multiple combinations

Use composite with ViewModel

summary

The use of ViewModel in Compose is consistent with Jetpack. Usually, when we build a page, if one piece of data needs to be used for multiple layouts, we can only pass it layer by layer in the formal parameters of the method. But this is obviously unreasonable and will reduce the readability of the code.

Using ViewModel can perfectly solve this problem. If you use ViewModel in Compose, you need to introduce the lifecycle ViewModel Compose library. The way to obtain ViewModel needs to use the extension function: viewModel()

In multiple @ Composable decorated functions, using viewModel() to obtain ViewModel can obtain the same ViewModel object, which is the fundamental reason why we can solve the problem

The above is limited to the same navigation page. If it is in different navigation pages, the viewmodels obtained are different objects, which is the same as that obtained in different activities

Dependency support

implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07'

code

@Composable
fun useWithViewModel() {
    val datas = remember {
        mutableStateListOf(
            ItemData(title = "towards ViewModel The value in is incremented by 1 and displayed", content = "0")
        )
    }
    val model: ExampleViewModel = viewModel()//Get ViewModel object
    Scaffold(topBar = {
        buildTopBar(title = "Compose and ViewModel Combination of")
    }) {
        ListView(
            datas = datas,
            state = rememberLazyListState(),
            click = { itemData: ItemData, index, _ ->
                model.increase()//Self increment of objects in ViewModel 1
                itemData.content = model.count.toString()//refresh data
                changeData(datas, index)
            })
    }
}

ExampleViewModel object

class ExampleViewModel: ViewModel() {
    fun increase() {
        count++
    }

    var count =0
}

Data Flow

summary

Compose can use Flow without importing dependencies. The usage is basically the same as. However, the use of StateFlow in compose does not require us to start the collect data collection Flow in the collaboration process. When using StateFlow, we can directly use Flow Collectasstate can obtain the value in StateFlow for display.

Sample code

The following code uses MutableStateFlow to realize data listening. When the MutableStateFlow value is updated, the function will be refreshed, and then use collectAsState to obtain the latest value for display.

Click the button below to change the value, and the content of the button above will be changed to show the effect

@Composable
fun useStateFlow() {
    var repository = remember {
        Repository()
    }
    Column {
        listItem(
            itemData = ItemData(
                title = "Click change StateFlow Value of",
                content = repository.stateFlow.collectAsState().value//Gets the value display in StateFlow
            ), onClick = {
            })
        changeUiWithState(repository)
    }

}

@Composable
fun changeUiWithState(repository: Repository) {
    listItem(itemData = ItemData(title = "Click change data"), onClick = {
        repository.increase()//Click the value to increase by 1
    })
}

class Repository {
    val stateFlow = MutableStateFlow("Initial value 0")
    var count = 0
    fun increase(): Int {
        stateFlow.value = count.toString()//Change the value in StateFlow
        return count++
    }
}

Operation effect

Hilt

Beginners can postpone the learning of hilt. Hilt is not a necessary and sufficient condition for learning Compose

The use of hilt is basically consistent with traditional development. You can see my other article article: https://juejin.cn/post/6967148539277213733

coil

coil is a picture library that can be used to load remote pictures in Compose

rely on

implementation 'io.coil-kt:coil-compose:1.3.2'

code

@Composable
fun useCoil() {
    val painter =
        rememberImagePainter(data = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201501%2F27%2F20150127103509_KvXhU.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631501719&t=9653a6a5bb4e29505b9b582c770b42ef",
            builder = {
                crossfade(true)
            })
    Image(
        modifier = Modifier
            .size(300.dp)
            .clip(shape = RoundedCornerShape(20.dp)),
        painter = painter,
        contentDescription = ""
    )
}

Various effects

Circular effect display

 rememberImagePainter(data = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201501%2F27%2F20150127103509_KvXhU.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631501719&t=9653a6a5bb4e29505b9b582c770b42ef",
            builder = {
                transformations(CircleCropTransformation())
            })

Fillet effect

  rememberImagePainter(data = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201501%2F27%2F20150127103509_KvXhU.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631501719&t=9653a6a5bb4e29505b9b582c770b42ef",
            builder = {
                transformations(
                    RoundedCornersTransformation()
                )
            })

Round and gray effect

  val painter =
        rememberImagePainter(data = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201501%2F27%2F20150127103509_KvXhU.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631501719&t=9653a6a5bb4e29505b9b582c770b42ef",
            builder = {
                transformations(
                    listOf(GrayscaleTransformation(), CircleCropTransformation())
                )
            })

Pay attention to official account and learn more knowledge

Topics: Android jetpack compose