ktolin+Jetpack Compose+协程Flow+MVVM

 最近看了很多jetpack Compose博文,因为自己也会flutter 所以尝试用用,因为大同,所以要看看不同的细节。

关于jetpack compose的文章大家可以去谷歌官网去看看,jetpack

Android studio环境

Android Studio Arctic Fox | 2020.3.1 Patch 1
 

添加框架

//网络加载框架
implementation "com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2"
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
//图片
implementation "io.coil-kt:coil-compose:1.3.2"

网络请求框架的准备

interface Api {

    companion object {

        const val HOME_URL = "https://www.wanandroid.com/"
    }

    @GET("article/list/0/json")
    suspend fun getHome(): HomeModel


}

//创建Retrofit对象
private val okHttpClient by lazy {
    OkHttpClient.Builder()
        .apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor { message -> Log.e(TAG, message) }.apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }
        .build()
}
private val  retrofit: Retrofit by lazy{
    Retrofit.Builder().baseUrl(Api.HOME_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

object ApiSever:Api by retrofit.create(Api::class.java)

创建仓库

class HomeRep {
    companion object {

        fun getHome(): Flow<HomeModel> = flow {
            val home = ApiSever.getHome()
            emit(home)

        }

    }

}

创建ViewModel

package com.it.myapplication.ViewModel

import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.it.myapplication.HomeRep
import com.it.myapplication.State
import com.it.myapplication.model.DatasBean
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 *
 * @class name:com.it.myapplication.ViewModel
 * @class describe
 *@class name:com.it.myapplication.ViewModel
 * @author XUIELIANG
 * @time 2021/8/30 0030 21:07
 * @change
 * @chang time
 * @class describe
 */
class HomeViewModel : ViewModel() {
    //val stateLists = MutableLiveData<State>(State.Empty)
     val stateLists:MutableState<State> =  mutableStateOf(State.Empty);

       init {

           getHome()
       }


    fun getHome() {
        viewModelScope.launch {
            HomeRep.getHome()
                .onStart {
                    stateLists.value = State.Loading()
                }.catch {
                    stateLists.value = State.Failed(it);
                }.collect { res ->
                    stateLists.value = State.Success(res)
                }


        }

    }


}

       jetpac compose

setContent {
            MyApplicationTheme {


                Surface(color = MaterialTheme.colors.background) {
                   when(val rel=homeModel.stateLists.value){
                       is State.Loading ->{
                           Log.e("=========","正在加载")
                       }
                       is State.Success->{
                           Toast.makeText(this, "加载成功", Toast.LENGTH_SHORT).show()

                           LayZyClodlme(data = rel.homeModel.data?.datas);
                           //Log.e("=========","加载成功==========${.toString()}")
                       }

                       is State.Failed->{
                           Toast.makeText(this, "加载失败", Toast.LENGTH_SHORT).show()
                           Log.e("=========","加载失败")
                       }
                   }

                }
            }
        }

   

@Composable
fun ComposableText(data: DatasBean) {

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .padding(start = 10.dp, end = 20.dp)
            .fillMaxWidth().clickable {

            }
    ) {
        Text(text = "${data.desc}===========")
        Image(painter = rememberImagePainter("https://www.wanandroid.com/blogimgs/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"), contentDescription = "",
            modifier = Modifier.size(200.dp)
            )
    }


}


@Composable
fun LayZyClodlme(data: List<DatasBean>?) {
    //val datas = listOf<String>("1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1")
    LazyColumn {


        data?.size?.let {
            items(count = it) { index ->
                ComposableText(data?.get(index))
            }
        }


    }

}

@Preview
@Composable
fun btn() {

    Button(onClick = { /*TODO*/
        Log.e("===============", "点击了")

    }) {
        Text(
            text = "点击", modifier = Modifier
                .fillMaxWidth()
                .padding(top = 20.dp)
        )
    }

}

@Composable
fun AlertDialogComponent() {
    val openDialog = remember { mutableStateOf(true) }
    if (openDialog.value) {
        AlertDialog(
            onDismissRequest = { openDialog.value = false },
            title = { Text(text = "Alert Dialog") },
            text = { Text("Hello! I am an Alert Dialog") },
            confirmButton = {
                TextButton(
                    onClick = {
                        openDialog.value = false
                        /* Do some other action */
                    }
                ) {
                    Text("Confirm")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        openDialog.value = false
                        /* Do some other action */
                    }
                ) {
                    Text("Dismiss")
                }
            },
            backgroundColor = Color.Black,
            contentColor = Color.White
        )
    }
}
//AndroidView

                                                                                                                                             

上一篇:WPF MVVM模式下的无阻塞


下一篇:vue到底是什么玩意