何时使用 MutableLiveData 和 LiveData

When to use MutableLiveData and LiveData

何时使用 MutableLiveDataLiveData 表示使用方法的区域:

MutableLiveData<User> getUser() {
    if (userMutableLiveData == null) {
        userMutableLiveData = new MutableLiveData<>();
    }
    return userMutableLiveData;
}

以及何时使用它,

LiveData<User> getUser() {
    if (userMutableLiveData == null) {
        userMutableLiveData = new MutableLiveData<>();
    }
    return userMutableLiveData
}

我们应该return LiveData 以防止视图(或其他观察者)意外修改值。

拥有:

    LiveData<User> getUser() {
       if (userMutableLiveData == null) {
           userMutableLiveData = new MutableLiveData<>();
       }
       return userMutableLiveData
    }

你不能在你的activity/片段中写:getUser().setValue(...)。这使您的代码更不容易出错。

假设您正在遵循 MVVM 架构 并且将 LiveData 作为从 ViewModelActivity 的可观察模式。这样您就可以将变量作为 LiveData 对象暴露给 Activity,如下所示:

class MyViewModel : ViewModel() {
    // LiveData object as following
    var someLiveData: LiveData<Any> = MutableLiveData()

    fun changeItsValue(someValue: Any) {
        (someLiveData as? MutableLiveData)?.value = someValue
    }
}

现在在 Activity 部分,您可以观察 LiveData 但要进行修改,您可以从 ViewModel 调用方法,如下所示:

class SomeActivity : AppCompatActivity() {
    // Inside onCreateMethod of activity
    val viewModel = ViewModelProviders.of(this)[MyViewModel::class.java]
    viewModel.someLiveData.observe(this, Observer{
        // Here we observe livedata
    })
    viewModel.changeItsValue(someValue) // We call it to change value to LiveData
    // End of onCreate
}

LiveData 没有 public 修改其数据的方法。

LiveData<User> getUser() {
    if (userMutableLiveData == null) {
        userMutableLiveData = new MutableLiveData<>();
    }
    return userMutableLiveData
}

您不能像 getUser().setValue(userObject)getUser().postValue(userObject)

那样更新它的值

所以当你不想修改你的数据时使用LiveData 如果您想稍后修改数据,请使用 MutableLiveData

当你不想修改它时使用 LiveData 因为像 setValue() & postValue 这样的方法() 不是 public。实时数据通过在内部调用它们自行处理。

在 MutableLiveData setValue() postValue() 中公开的地方,即 public.You 可以通过调用这些来更改设置值方法。

在此处查找更多详细信息: https://blog.mindorks.com/livedata-setvalue-vs-postvalue-in-android

单独使用 MutableLiveData 的最佳方法 class 卢克

public class SharedViewModel extends ViewModel {
private MutableLiveData<CharSequence>text = new MutableLiveData<>();

public void setText(CharSequence input)
{
    text.setValue(input);
}

public LiveData<CharSequence> getText(){
    return text;

}
}

Livedata在Fragment Like中使用

private SharedViewModel viewModel;

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //No Need to initate further
        viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        viewModel.getText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
            @Override
            public void onChanged(@Nullable CharSequence charSequence) {
                editText.setText(charSequence);
            }
        });
    }

在片段中 Class 点赞

public class FragmentA extends Fragment {
    private SharedViewModel viewModel;
    private EditText editText;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_a, container, false);
        editText = v.findViewById(R.id.edit_text);
        Button button = v.findViewById(R.id.button_ok);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.setText(editText.getText());
            }
        });
        return v;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        viewModel.getText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
            @Override
            public void onChanged(@Nullable CharSequence charSequence) {
                editText.setText(charSequence);
            }
        });
    }
}

对于最佳实践、可读性和避免错误倾向,就像 Kotlin 中的 MutableListList 一样。使用 Mutable 是当你想修改它的数据或者你想在它上面重新分配一个新值时。

当我们想让它的值可写或可以随时更改时,我们使用 MutableLiveData

当我们只想阅读和收听 MutableLiveData 所做的任何更新时,我们使用 LiveData。因此我们有这种代码作为示例

private var filterAsset = MutableLiveData<String>().apply{
        value = "Empty"
    }

    //public method to set a new value on filterAsset
    fun setFilterData(assetName: String){
        filterAsset.value = assetName
    }

// We can use this to listen on any updates from filterAsset
val assetFilterUpdates: LiveData<String> = filterAsset


// Inside your Fragment/Activity
// You can listen to the update in Fragment or Activity like this 
yourViewModel.assetFilterUpdates.observe(viewLifecycleOwner, { value ->

            // Use the updated value here

        })

LiveData 没有 public 可用的方法来更新存储的数据。 MutableLiveData class 公开了 setValue(T)postValue(T) 方法 public 如果您需要编辑存储在 LiveData 中的值,则必须使用这些方法目的。通常 MutableLiveDataViewModel 中使用,然后 ViewModel 只向观察者公开不可变的 LiveData 对象。 请看看这个reference.