使用单例拓展LiveData对象,可以在您的app全局使用。LiveData一旦与service构建联系,通过observer观察者,即可更新数据源。
下面举例说明
- 构建SyncLiveData继承LiveData
- 构建SyncService
- SyncFragment
- Fragment通过SyncLiveData观察LiveData数据发生变化后,可以做相关UI更新。
- LiveData通过Service发生数据更新。
一、构建SyncLiveData类
public class SyncLiveData extends LiveData<SpannableStringBuilder> {
private static SynLiveData sInstance;
private final static SpannableStringBuilder log = new SpannableStringBuilder("");
@MainThread
public static SynLiveData get() {
if (sInstance == null) {
sInstance = new SynLiveData();
}
return sInstance;
}
private SynLiveData() {
}
public void appendLog(String text) {
log.append(text);
postValue(log);
}
public void appendLog(Spanned text) {
log.append(text);
postValue(log);
}
}
二、在SyncService处理数据更新
下面会更新 LiveData
SyncLiveData.get().appendLog(message);
使用LiveData的方法setValue(…) or postValue(…)通知观察者刷新UI
SyncLiveData.get().setValue(message);
三、构建UI类SyncFragment
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
//...
// Create the observer which updates the UI.
final Observer<SpannableStringBuilder> ETAObserver = new Observer<SpannableStringBuilder>() {
@Override
public void onChanged(@Nullable final SpannableStringBuilder spannableLog) {
// Update the UI, in this case, a TextView.
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
textViewLog.setText(spannableLog);
}
});
}
};
// Observe the LiveData, passing in this activity/fragment as the LifecycleOwner and the observer.
SyncLiveData.get().observe(getViewLifecycleOwner(), ETAObserver);
//...
}
下面是activity观察模式
SyncLogLiveData.get().observe(this, ETAObserver);
当然,您可以捕获LiveData的数据
SyncLogLiveData.get().getValue();
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)