【问题标题】:How to pass result of livedata as a function argument using kotlin如何使用 kotlin 将 livedata 的结果作为函数参数传递
【发布时间】:2021-05-22 20:45:53
【问题描述】:

如何使用 livedata 作为另一个函数的参数?每次我得到一个空值时,我猜在 livedata 可以返回之前调用该函数,因此是空值。我没有从视图中使用它。我从视图模型中使用它,函数 updateFirstName 来自视图模型。令牌作为来自 Preference Store 的 Flow。感谢所有答案。

    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)
                }

            })
        }
    }```

【问题讨论】:

    标签: android kotlin android-livedata kotlin-flow


    【解决方案1】:

    可以观察到 LiveData,这使您能够以这种方式“读取”它:

    yourModel.token.observe(viewLifecycleOwner) { token ->
    
        //Here do whatever you like with "token"
    
    }
    
    

    【讨论】:

    • 我没有从视图中使用它。我在视图模型中使用它,函数 updateFirstName 来自视图模型。
    • 你不能在片段中移动那个函数并使用观察者吗?
    • 我做到了,它奏效了,但这不是我想要的。我的方法有问题吗?
    • 我没有看到任何问题,尽管我认为 ViewModel 中有逻辑是不寻常的,它应该用作 UI 和逻辑之间的桥梁(如果我是,请纠正我错了,我还在这里学习!)。我学到的方法是在 ViewModel 中设置实时数据变量并在片段中观察它们以进行操作。
    • 我认为在 MVVM 中 View(fragemnt, activity, xml) 应该是哑的,逻辑应该在 Viewmodel 中实现。
    【解决方案2】:

    首先,您的视图模型中不应有“视图”引用,因为这会将您的视图模型与其给定视图(可能是片段?)耦合。

    所以你的函数updateFirstName(view:View)应该改成updateFirstName(name: String)

    其次,我认为您使用错误的存储库。与其从存储库中获取 liveData,然后将其转换为 MutableLiveData,不如公开一个存储库函数,该函数会保存您的给定名称。

    视图唯一应该做的就是观察值和暴露事件。仅此而已。

    这可能是一个解决方案:

    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
          }
       }
    }
    

    此外,如果您想在视图模型中使用令牌并“观察”它,您可以开始在函数内收集流,然后使用它的值:

    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.
          }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      相关资源
      最近更新 更多