基于LiveData的Service刷新UI

前言

使用单例拓展LiveData对象,可以在您的app全局使用。LiveData一旦与service构建联系,通过observer观察者,即可更新数据源。
下面举例说明

  1. 构建SyncLiveData继承LiveData
  2. 构建SyncService
  3. SyncFragment
  4. Fragment通过SyncLiveData观察LiveData数据发生变化后,可以做相关UI更新。
  5. 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();

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值