architecture-components-samples
architecture-components-samples copied to clipboard
if I get new LiveData response from Repository everytime, how to set value to val LiveData in ViewModel without Transformations.switchMap()?
I have a question.
in browseSample we always Transformations.switchMap()
to observe one input LiveData and set the value of repoRepository.search(search)
to results. As below:
val results: LiveData<Resource<List<Repo>>> = Transformations
.switchMap(_query) { search ->
if (search.isNullOrBlank()) {
AbsentLiveData.create()
} else {
repoRepository.search(search)
}
}
but in my case I just click button to get the new results by repoRepository.search(search)
every time, this means I don't have param _query
to observe. how can I do?
I already defined results
as val, so I can't make results = repoRepository.search(search)
in ViewModel everyTime.
If I change the repoRepository return type from LiveData<Result> to Result, then I can use results.setValue(result) manually in ViewModel. but is that right to return non-LiveData reuslt from Repository?
I'm very confused about that...... in many cases we don't have input params to Observe so we can't use Transformations.switchMap()
我也遇到了同样的问题:
如果我只想点击按钮获取数据,没有任何参数的变化,我将无法使用Transformations .switchMap
,那么如何保证LiveData
的唯一?每次从Repository
返回的都是一个新的LiveData
,如何将Repository
每次返回的LiveData
转换为ViewModel
中被Activity
监听的LiveData
,并且保证LiveData
对象永远是同一个对象呢?如果你找到了解决方案,希望分享一下,谢谢!
I had the same problem:
If I only want to click on the button to get the data, without any parameter changes, I will not be able to use Transformations .switchMap
, so how to ensure that LiveData
is unique?Each time LiveData
returns from Repository
is a new LiveData
. How to convert LiveData
returned by Repository
into LiveData
in ViewModel
monitored by Activity
, and ensure that LiveData
is always the same object?
16days past, it seems nobody care this question . if I find the best solution whick can point the val LiveData in ViewModel to the new LiveData from repository, I'll tell you.
I had the same problem
I can think about one way of doing it: using MediatorLiveData
. You can use mediator to observe a click event (using SingleLiveEvent
from Google) and set the value to the repository call and observe the changes from the search text and get the same result as the code you have posted here. Wrapping the mediator you created in a switchMap should give you the wanted result.
https://developer.android.com/topic/libraries/architecture/coroutines There is a liveData construct with coroutines. Hope this helps. You can also refer to https://github.com/nagaprakash2020/Dictionary for example