当前位置 : 主页 > 手机开发 > android >

android – 在Viewmodel中访问BroadCastReceiver

来源:互联网 收集:自由互联 发布时间:2021-06-11
我真的很难选择正确的方法将数据从broadcastReceiver传递到ViewModel,并从那里我将数据传递给我的存储库并更新LiveData.我使用FCM推送通知,并使用ActivityLifecycle的本地broadCastReceiver.我发现从
我真的很难选择正确的方法将数据从broadcastReceiver传递到ViewModel,并从那里我将数据传递给我的存储库并更新LiveData.我使用FCM推送通知,并使用ActivityLifecycle的本地broadCastReceiver.我发现从BroadcastReceiver访问ViewModel是不好的做法,但不确定为什么?如果我管理broadcastReceiver的生命周期,它不应该导致任何问题……那么将接收到的数据从FCM传递到我的Repository的MediatorLiveData的最佳方法是什么?我使用MediatorLiveData,因为我添加了不同的LiveData源(API请求和FCM).将不胜感激的建议和实施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);
    }
}
网友评论