简体   繁体   English

如何使用 kotlin 将 livedata 的结果作为 function 参数传递

[英]How to pass result of livedata as a function argument using kotlin

How to use a livedata as an argument for another function?如何使用 livedata 作为另一个 function 的参数? Every time I get a null value, I guess the function is called before the livedata can return hence the null value.每次我得到一个 null 值时,我猜想在 livedata 可以返回之前调用 function 因此 null 值。 I'm not using it from a View.我没有从视图中使用它。 I'm using it from the viewmodel, the function updateFirstName is from the viewmodel.我从视图模型中使用它,function updateFirstName 来自视图模型。 The token comes as a Flow from the Preference Store.令牌作为来自 Preference Store 的 Flow。 All answers are appreciated thanks.感谢所有答案。

    var token: LiveData<String> = appPreferenceStorage.accessToken.asLiveData()

    @ExperimentalCoroutinesApi
    private val _token: MutableLiveData<String>
        get() = token as MutableLiveData<String>
    fun updateFirstName(view: View) {
        viewModelScope.launch {

            profileRepository.updateFirstName(_token.value.toString(), "Bob", object : ProfileListener {
                override fun onSuccess(response: String?) {
                    Timber.d(response)
                }

                override fun onFailure(localizedMessage: String?) {
                    Timber.e(localizedMessage)
                }

            })
        }
    }```

LiveData can be observed which gives you the ability to "read" it this way:可以观察到 LiveData,这使您能够以这种方式“读取”它:

yourModel.token.observe(viewLifecycleOwner) { token ->

    //Here do whatever you like with "token"

}

First, there should be no "view" references inside your viewmodel, as this would couple your viewmodel with it's given view (fragment perhaps?).首先,您的视图模型中不应该有“视图”引用,因为这会将您的视图模型与其给定的视图(也许是片段?)耦合起来。

So your function updateFirstName(view:View) should be changed to updateFirstName(name: String)所以你的 function updateFirstName(view:View)应该改为updateFirstName(name: String)

Second, I think you are using your repository wrong.其次,我认为您使用错误的存储库。 Instead of getting a liveData from your repository and then converting it into a MutableLiveData, you should just expose a repository function, which saves your given name.与其从存储库中获取 liveData,然后将其转换为 MutableLiveData,不如只公开存储库 function,它会保存您的给定名称。

The only thing a view should do is to observe values and expose events.视图唯一应该做的就是观察值和暴露事件。 Nothing more.而已。

This could be a solution:这可能是一个解决方案:

class YourViewModel(private val repository: IYourRepositoryInterface) : ViewModel() {
   // Token should only be observed from a view and not converted to a MutableLiveData
   val token: LiveData<String> = appPreferenceStorage.accessToken.asLiveData()

   fun updateFirstName(name: String) {
      viewModelScope.launch {
          repository.updateFirstName(name) // suspend function from your repository
      }
   }
}

Furthermore, if you want to use your token inside your viewmodel and "observe" it, you can just start collecting the flow inside a function and then use its value:此外,如果您想在视图模型中使用令牌并“观察”它,您可以开始在 function 中收集流,然后使用它的值:

val token: Flow<String> = appPreferenceStorage.accessToken

fun someFunctionThatDoesStuffWithToken() {
    viewModelScope.launch {
      token.collect { value: String ->
        // do something with its value. E.g: Write into repository, db etc.
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Kotlin lambda 传递返回 LiveData 的回调 function? - How do you pass a callback function that returns a LiveData using Kotlin lambdas? 如何将 editText 值传递给 viewModel 和 Livedata (Kotlin) - How to pass editText value to viewModel and Livedata (Kotlin) 在 Kotlin 协程中等待 LiveData 结果 - Wait for LiveData result in a Kotlin coroutine 如何调用作为另一个 function 结果的特定命名参数? Kotlin - How to call specific named argument which is a result of another function? Kotlin 如何在隐式调用时自动将参数传递给 function kotlin - How to automatically pass an argument to a function when it is called implicitly kotlin 如何使用 Kotlin DSL 在 Android 导航中传递参数 - How to pass argument in Android Navigation using Kotlin DSL 如何使用 LiveData 在片段之间传递数据 - how pass data between fragments using LiveData Kotlin:如何在 viewModel 中观察一次 liveData ? 使用 ObserveForever() 和 removeObserver() - Kotlin: How to Observe Once a liveData in a viewModel ? Using ObserveForever() and removeObserver() Kotlin/Android:无法使用 Canvas 将 LiveData 传递给 customView - Kotlin/Android : Cannot pass LiveData to customView with Canvas 如何结合 livedata 和 kotlin 流 - How to combine livedata and kotlin flow
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM