如何使用 Jetpack Compose 动态调用具有不同参数的视图模型?

How to call viewmodel dynamically with difference params with jetpack compose?

第一次运行,这些代码工作正常。使用默认参数显示来自 Firestore 的数据。但是,如果我根据 selectedDropdown 更改参数,则不会检索到任何数据。我用 modelFactory

这是我的MainActivityclass

Column() {
    Column {
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier
                .width(with(LocalDensity.current) { textfieldSize.toDp() })
        ) {
            suggestions.forEach { label ->
                DropdownMenuItem(onClick = {
                    selectedText = label
                    pompaId = label.replace(" ", "").lowercase() // 1. parameter value based on this
                    expanded = !expanded
                }) {
                    Text(text = label)
                }
            }
        }
    }
    KalibrasiList(pompaId) //2. this called everytime dropdown was changed
    
}

可组合函数

@Composable
fun KalibrasiList(
    pompaId: String,
    kalibrasiViewModel: KalibrasiViewModel = viewModel(
        factory = KalibrasiViewModelFactory(pompaId, KalibrasiRepository()) //3. this fired once even parameter was change. (I need this fired follow dropdown change, so firestore can fired to retrieve data)
    )
) {
    when (val kalibrasiList = kalibrasiViewModel
        .response
        .asStateFlow()
        .collectAsState()
        .value) {

        is OnSuccess -> {
           // my code here..
        }
}

模型工厂

class KalibrasiViewModelFactory(
    private val pompaId: String,
    private val kalibrasiRepository: KalibrasiRepository
) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(KalibrasiViewModel::class.java)) {
            return KalibrasiViewModel(pompaId, kalibrasiRepository) as T
        }
        throw IllegalStateException()
    }
}

视图模型class

class KalibrasiViewModel(val pompaId: String,val kalibrasiRepository: KalibrasiRepository): ViewModel() {

    val response = MutableStateFlow<Response?>(null)

    init {
        viewModelScope.launch {
            kalibrasiRepository.getList(pompaId).collect {
                response.value = it
            }
        }
    }
}

存储库class

class KalibrasiRepository {
    private val firestore = FirebaseFirestore.getInstance()
    @OptIn(ExperimentalCoroutinesApi::class)
    fun getList(pompaId: String) = callbackFlow {
        val collection = firestore.collection("colCalibrate")
            .whereEqualTo("pompaId", pompaId)
            .orderBy("createdAt", Query.Direction.DESCENDING)
        val snapshotListener = collection.addSnapshotListener { value, error ->
            val response = if (error == null) {
                OnSuccess(value)
            } else {
                OnError(error)
            }

            this.trySend(response).isSuccess
        }

        awaitClose {
            snapshotListener.remove()
        }
    }

}

我想在每次更改下拉值时加载数据。

您可以使用 viewModelkey 参数:它会为每个唯一的 key.

创建一个新的视图模型
kalibrasiViewModel: KalibrasiViewModel = viewModel(
        key = pompaId,
        factory = KalibrasiViewModelFactory(pompaId, KalibrasiRepository(),
    )
)