【问题标题】:Trying to get ViewModel in @Composable试图在@Composable 中获取 ViewModel
【发布时间】:2021-10-07 08:13:35
【问题描述】:

我正在尝试学习jetpack compose。我被 ViewModel 卡住了。

我有一个视图模型

class DataViewModel: ViewModel() {

    //the list of live data
    var listData = mutableListOf<Data>()

    //initialize the viewmodel
    init {

        viewModelScope.launch {
            //do the network call (this is working ok)
            val data = fetchData()
            data.forEach {
                listData.add(it)
                //print the list of data, this is working fine
                println("listData")
            }

        }
    }

因此,获取数据并将其放入 dataList 工作正常。但不,我想在我的屏幕上显示数据。我做了一个可组合的

@Composable
//pass in the viewmodel
fun DataScreen(model:DataViewModel = viewModel()){
    println("model.listData")
    this return an empty list ?
    Column{
        model.listData?.forEach { item ->

            Text("${item}")

            }
        }

   }

在我的屏幕上没有任何反应,因为它是可组合物中的一个空列表。 如何从 ViewModel 中获取列表?

【问题讨论】:

  • 为您的列设置修饰符Modifier.fillMaxSize()
  • 我从视图模型中得到的列表是空的,所以我认为这不会有什么不同

标签: android kotlin android-jetpack-compose android-jetpack


【解决方案1】:

问题是您没有在视图模型中使用 State 值。需要状态才能为可组合重组注册您的值(以防分配/更改值)

所以你需要有这样的视图模型(我猜你的 fetchData 是一个挂起函数):

   class DataViewModel: ViewModel() {

    //the list of live data
    val listDataState = MutableState<List<Data>> =  mutableStateOf(emptyList<Data>())

    //initialize the viewmodel
    init {

        viewModelScope.launch {
            val data = fetchData()
            listDataState.value = data

        }
    }

    suspend fun fetchData() : List<Data>{
        //something like: 
        return dataRepository.getData()
    }

   }

然后在你的@Composable 函数中你会得到这样的数据:

val viewModel: DataViewModel = viewModel()
val data = viewModel.listDataState.value

【讨论】:

  • tx,这将完成这项工作,它的工作。是的,网络呼叫被暂停。一个问题。在 MutableState> 或 MutableLiveData 之间创建实时数据列表有什么区别?
  • 您实际上可以使用实时数据,只是 MutableState 针对 Jetpack Compose 进行了优化,以便轻松使用。看到这个:youtu.be/QDcBO4iROyE?t=471
猜你喜欢
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2012-06-13
  • 2017-09-07
相关资源
最近更新 更多