我真的很难选择正确的方法将数据从broadcastReceiver传递到ViewModel,并从那里我将数据传递给我的存储库并更新LiveData.我使用FCM推送通知,并使用ActivityLifecycle的本地broadCastReceiver.我发现从
我考虑过从BroadCastReceiver访问Repository,如下所示:
RepositoryMain.getSingletonInstance()setResponse(状态).
您需要定义单一事实来源(SSoT).在你的情况下它是Repository(如果Repository封装了db持久性存储,SSoT就是db).现在您需要实现从接收器到通过SSoT(Repository)查看的数据流,如下例所示:接收器实施
public class FcmReceiver extends BroadcastReceiver { private final MutableLiveData<MyData> mData = new MutableLiveData<>(); public LiveData<MyData> getData() { return mData; } @Override public void onReceive(Context context, Intent intent) { // entry point of data mData.setValue(new MyData()); } }
知识库
public class Repository { private static final Repository INSTANCE = new Repository(); private final MediatorLiveData<MyData> mData = new MediatorLiveData<>(); private Repository() {} public static Repository instance() { return INSTANCE; } public LiveData<MyData> getData() { return mData; } public void addDataSource(LiveData<MyData> data) { mData.addSource(data, mData::setValue); } public void removeDataSource(LiveData<MyData> data) { mData.removeSource(data); } }
查看模型
public class MyViewModel extends ViewModel { public LiveData<MyData> getData() { // for simplicity return data directly to view return Repository.instance().getData(); } }
活动
接收器数据和存储库有绑定
public class MainActivity extends AppCompatActivity { private FcmReceiver mReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mReceiver = new FcmReceiver(); } @Override protected void onStart() { super.onStart(); // add data source Repository.instance().addDataSource(mReceiver.getData()); registerReceiver(mReceiver, IntentFilter.create("action", "type")); } @Override protected void onStop() { super.onStop(); // don't forget to remove receiver data source Repository.instance().removeDataSource(mReceiver.getData()); unregisterReceiver(mReceiver); } }