我正在使用BroadcastReceiver中的LiveData和Room Database。
主要思想是对数据库执行单个查询(插入,删除,获取),并将更新后的值转发给调用方。
借助观察者收听 LiveData 对象,我能够获取更新后的值。然后,该值通过 setResultData()转发给调用方。
这是我的BroadcastReceiver:
public class WordReceiver extends BroadcastReceiver {
...
private List<Sring> mWordList;
private WordItemViewModel mWordItemViewModel;
private Observer<List<String>> mObserver;
private boolean mActionPerformed = false;
...
@Override
public void onReceive(final Context context, final Intent intent) {
final PendingResult result = goAsync();
new Thread() {
public void run() {
manageActions(context, intent, result);
}
}.start()
}
...
private void manageActions(Context context, Intent intent, PendingResult result) {
String action = intent.getAction();
if (action == null) {
return;
}
switch (action) {
case WordReceiver.ACTION_ADD_WORD:
initVariables(context, result);
mActionPerformed = true;
mWordItemViewModel.insert(intent.getStringExtra(WordReceiver.EXTRA_WORD);
break;
case WordReceiver.ACTION_REMOVE_WORD:
initVariables(context, result);
mActionPerformed = true;
mWordItemViewModel.delete(intent.getStringExtra(WordReceiver.EXTRA_WORD);
break;
case WordReceiver.ACTION_GET_WORDS:
// mActionPerformed is set to true because there is no action to perform
mActionPerformed = true;
initVariables(context, result);
break;
default:
result.abortBroadcast();
break;
}
}
}
观察者和 AndroidViewModel 是通过以下方式初始化的:
private void initVariables(final Context context, final PendingResult result) {
mWordItemViewModel = ViewModelProvider.AndroidViewModelFactory.getInstance((Application) context.getApplicationContext()).create(WordItemViewModel.class);
mObserver = new Observer<List<String>>() {
@Override
public void onChanged(@Nullable final List<String> wordList) {
mWordList = wordList;
if (mActionPerformed) {
mWordItemViewModel.getAllWordItems().removeObserver(this);
if (mWordList != null) {
String wordListText = TextUtils.join(",", mWordList);
result.setResultData(wordListText);
}
result.finish();
}
}
};
mWordItemViewModel.getAllWordItems().observeForever(mObserver);
}
这有效,但并非总是如此!
有时 onChanged()中的 wordList 参数会考虑已添加/已删除的Word,有时没有考虑。
根据https://developer.android.com/reference/android/arch/lifecycle/LiveData#getvalue
返回当前值。请注意,在 后台线程不保证最新值设置为 收到。
我没有使用 getvalue(),但是我想知道 onChanged()方法是否可能具有相同的行为。
非常感谢...