【问题标题】:How to dynamically pass parameters in the Android ViewModel?How to dynamically pass parameters in the Android ViewModel?
【发布时间】:2022-12-01 23:17:32
【问题描述】:

In the following variables, how do I dynamically pass user.id and friend.id


class WindViewModel @Inject constructor() : BaseViewModel() {

    val userWindList = Pager(config = pagingConfig, remoteMediator = WindRemoteMediator("userWindList", user.id, friend.id, database!!, api)) {
        windRepository.pagingModelList(friend.id, "userWindList")
    }.flow.map { pagingData ->
        pagingData.map { it.json.toWind() }
    }.cachedIn(viewModelScope)
}

【问题讨论】:

  • By dynamic, do you mean at the time viewModel is created ( like passing in the constructor) or during runtime?

标签: android kotlin android-viewmodel


【解决方案1】:

The way to pass arguments dynamically on a Kotlin function is like this:

...
val sumOfSomeInts = sumOfSomeInts(1, 3, 7, 2)
...
fun sumOfSomeInts(vararg num: Int): Int {
    var sum = 0
    ...
    return sum
} 
...

However, I would suggest you leave vararg parameters on the front of the parameters list, or at least you use named arguments like in this answer

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 2022-12-01
    • 2022-02-24
    • 2016-11-14
    • 2022-12-02
    • 2022-12-02
    • 2022-12-02
    • 2022-12-27
    • 2022-12-16
    相关资源
    最近更新 更多