简体   繁体   English

如何将逻辑提取到 viewModel?

[英]How can I extract logic to viewModel?

In my fragment I have next code:在我的片段中,我有下一个代码:

etAuthorName.doAfterTextChanged {
    viewModel.quoteAuthor.value = it?.toString()
}

viewModel.quoteAuthor.observe(this, Observer<String> {
    if (etAuthorName.text.toString() != it) {
        etAuthorName.setText(it)
    }
})

How i can extract this logic: if (etAuthorName.text.toString() != it) to my viewModel?我如何提取这个逻辑: if (etAuthorName.text.toString() != it)到我的viewModel?

You can use databinding in this case, learn more here: https://developer.android.com/topic/libraries/data-binding在这种情况下,您可以使用数据绑定,在此处了解更多信息: https://developer.android.com/topic/libraries/data-binding

Edit: You can try something like this:编辑:你可以尝试这样的事情:

In your ViewModel class:在您的 ViewModel class 中:

@get:Bindable
var bindetAuthorName: String = ""
    set(value) {
        field = value
        notifyPropertyChanged(BR.bindetAuthorName)
    }
    get() = field

fun comparison(){
    if(bindetAuthorName != quoteAuthor){
        bindetAuthorName = quoteAuthor
    }
}

in your xml edittext/ textview:在您的 xml 编辑文本/textview 中:

<Edittext
 .....
 android:text="@={viewModel.bindetAuthorName}"/>

and whenever your quoteAuthor value is updating you can call comparison().并且每当您的 quoteAuthor 值更新时,您都可以调用 compare()。 I hope this helps!我希望这有帮助!

You can use Transformations.distinctUntilChanged add this inside viewmodel and listen inside your fragment instead observer quoteAuthor您可以使用Transformations.distinctUntilChanged在视图模型中添加它并在您的片段中收听而不是观察者 quoteAuthor

val authorDistinct = Transformations.distinctUntilChanged(quoteAuthor)

In order to really move your logic to ViewModel为了真正将您的逻辑转移到 ViewModel

You can change it to this你可以把它改成这个

Fragment分段

etAuthorName.doAfterTextChanged {
    viewModel.triggerQuoteAuthor(etAuthorName.text.toString(), it?.toString())
}

viewModel.quoteAuthor.observe(this, Observer<String> {
    etAuthorName.setText(it)
})

ViewModel视图模型

fun triggerQuoteAuthor(beforeText: String, afterText: String) {
   if (beforeText != afterText) {
      quoteAuthor.value = afterText
   }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM