有两种方法可以改变价值MutableLiveData.但是,什么是区别setValue()与postValue()在MutableLiveData.
我找不到相同的文档.
这是MutableLiveDataAndroid 类.
package android.arch.lifecycle;
/**
* {@link LiveData} which publicly exposes {@link #setValue(T)} and {@link #postValue(T)} method.
*
* @param <T> The type of data hold by this instance
*/
@SuppressWarnings("WeakerAccess")
public class MutableLiveData<T> extends LiveData<T> {
@Override
public void postValue(T value) {
super.postValue(value);
}
@Override
public void setValue(T value) {
super.setValue(value);
}
}
Run Code Online (Sandbox Code Playgroud) 更新: 如果我移动到另一个片段并返回到这个片段,TextView 会更新......
我无法通过使用 setValue() 或 postValue() 使 UI 中的 MutableLiveData 更新为新值。我可以通过将 MutableLiveData 更改为 ObservableData 来使其工作,但重点是使用 LiveData 而不是 ObservableData。
我在其他视图中也有类似的工作没有问题。不确定这里发生了什么......我唯一能想到的是我在相机活动(通过意图)和这个片段之间来回跳跃。在活动结果上,我将片段中的数据设置到 ViewModel。
我不相信我需要为片段中的值设置任何观察者,因为我在 XML 和 ViewModel 之间有 2 路数据绑定。
my_fragment.XML
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="myViewModel"
type="com.example.myapplication.MyViewModel" />
</data>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@={myViewModel.photosCount}"
tools:text="1" />
<Button
android:id="@+id/btnTakePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take Picture"
android:onClick="@{myViewModel::navClicked}"/>
</LinearLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)
视图模型.java
private MutableLiveData<String> photosCount = new MutableLiveData<>();
private MutableLiveData<Boolean> takePhoto = new MutableLiveData<>();
public MyViewModel() {
photosCount.setValue("0"); // …Run Code Online (Sandbox Code Playgroud) 我目前有一个包含MyItem,并使用 Firebase/LiveData的列表的项目。它被组织成组,每个组都有项目。
如果发生以下任何情况,我希望能够更新此列表:
为了获取内容列表,我有一个像这样的函数来返回 LiveData,每当一个项目更新(#1)时它就会更新。
getList(id: String): LiveData<List<MyItem>> {
val data = MutableLiveData<List<MyItem>>()
firestore
.collection("groups")
.document(id)
.collection("items")
.addSnapshotListener { snapshot, exception ->
val items = snapshot?.toObjects(MyItem::class.java) ?: emptyList()
// filter items
data.postValue(items)
}
return data
}
Run Code Online (Sandbox Code Playgroud)
在我的 ViewModel 中,我有处理这种情况的逻辑。
private val result = MediatorLiveData<Resource<List<MyItem>>>()
private var source: LiveData<List<MyItem>>? = null
val contents: LiveData<Resource<List<MyItem>>>
get() {
val group = database.group
// if the selected group is changed.
return Transformations.switchMap(group) …Run Code Online (Sandbox Code Playgroud) android kotlin android-livedata google-cloud-firestore mutablelivedata
我知道MutableLiveDataextends LiveData,但它们之间有什么区别(在使用中)。什么是合适的用例,意味着什么时候从两者中使用正确的一个?
我一直在使用这里SingleLiveData可以找到的课程.我的问题是:
是SingleLiveData实际上是Android架构组件的一部分?
使用它是个好主意吗?
android android-livedata android-architecture-components mutablelivedata
LiveData开始观察时是否可以防止接收到最后一个值?我正在考虑LiveData用作事件。
例如类似于show message,导航事件或对话框触发器之类的事件EventBus。
ViewModel与片段之间的通信有关的问题,Google给我们LiveData提供了用数据更新视图的方法,但是这种类型的通信不适用于仅需通过单个事件更新视图一次的情况,也无法保存视图的引用ViewModel并调用某些方法,因为它将导致内存泄漏。
我发现了类似的SingleLiveEvent-但它仅适用于1个观察者,不适用于多个观察者。
android android-livedata android-architecture-components mutablelivedata
我有一项活动正在观察存储库中的实时数据。现在,当活动被销毁然后再次创建时,我仍然从存储库中获取旧值,除非我手动获取新值。
为什么即使观察者活动被销毁,可变的实时数据仍保留其旧值?
我的 ViewModel 中有两个变量,它们由用户使用按钮控制。他可以通过单击适当的按钮来减少或增加值。
val age = MutableLiveData<Int>().apply { value = 0 }
val weight = MutableLiveData<Double>().apply { value = 0.0 }
现在我只想在两个变量的值都大于 0 时启用保存按钮。怎么做?我想过在 ViewModel 中创建另一个 LiveData 变量correctData或以某种方式观察 Activity 中的年龄和体重变量,但我需要帮助,因为我不知道该怎么做。
谢谢你的帮助。
更新
我创建了 MediatorLiveData 并且它几乎可以正常工作,几乎是因为它没有检测到两个来源是否都提供了真正的价值,但是否有任何真正的价值。
private val _correctData = MediatorLiveData<Boolean>().apply {
value = false
addSource(age) { x -> x?.let { value = x > 0 } }
addSource(repeats) { x -> x?.let { value = x > 0 } }
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
我有两个 Activity 和一个 Fragment。我想在这些活动之间共享数据。事实上,当用户在MainActivity中更改FragmentA时,必须自动更新SecondActivity中的FragmentA。
我的视图模型:PlayerFragmentVM.java
public class PlayerFragmentVM extends ViewModel {
private MutableLiveData<Boolean> btnFavoriteClickedLiveData;
public PlayerFragmentVM(){
btnFavoriteClickedLiveData = new MutableLiveData<>();
}
public MutableLiveData<Boolean> getBtnFavoriteClickedLiveData() {
return btnFavoriteClickedLiveData;
}
}
Run Code Online (Sandbox Code Playgroud)
PlayerFragment.java
public class PlayerFragment extends Fragment {
private FragmentPlayerBinding fragmentPlayerBinding;
private PlayerFragmentVM playerFragmentVM;
private ShineButton btnFavorite;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//init view binding
fragmentPlayerBinding = FragmentPlayerBinding.inflate(inflater, container, false);
View view = fragmentPlayerBinding.getRoot();
//init ViewModel
playerFragmentVM = ViewModelProviders.of(this).get(PlayerFragmentVM.class);
//button checked change listener
btnFavorite.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
@Override …Run Code Online (Sandbox Code Playgroud) android android-fragments android-fragmentactivity android-livedata mutablelivedata
我有一个存储库类,它使用 MutableLiveData 对象(仅公开为 LiveData),将异步 Web 查询的结果返回到 ViewModel。然后,ViewModel 使用 Transformation 将结果映射到视图观察到的另一个 MutableLiveData。
我认为我通过分离关注点来遵循此模块中推荐的架构,但我发现很难为 ViewModel 编写单元测试:
class DataRepository ( private val webservice: DataWebService ) {
private val _exception = MutableLiveData<Exception?>(null)
val exception : LiveData<Exception?> get() = _exception
private val _data = MutableLiveData<List<DataItem>>()
val data: LiveData<List<DataItem>> = _data
private val responseListener = Response.Listener<String> {response ->
try {
val list = JsonReader(SearchResult.mapping).readObject(response).map {
//Data transformation
}
_exception.value = null
_data.value = list
} catch (ex: Exception) {
_exception.value = ex
_data.value = emptyList()
} …Run Code Online (Sandbox Code Playgroud) android ×10
android-livedata ×10
mutablelivedata ×10
android-architecture-components ×2
kotlin ×2
android-mvvm ×1
junit ×1
mockito ×1