Android MVVM:观察广播接收器的数据库更改

问题描述 投票:0回答:1

在我的应用程序中,我需要从BroadcastReceiver添加/删除/更新我的数据库中的数据。我想知道这方面的最佳做法是什么。由于在主线程上调用onReceive,我需要一种在工作线程上运行查询的方法,并且在完成时我需要onReceive方法中的响应。

为此,我使用了一个简单的Observer模式。

public class NetworkChangeReceiver extends BroadcastReceiver implements IDbUpdateListener{

    private MyRepository repo;

    private Application application;

    @Override
    public void onReceive(Context context, Intent intent) {
                //Some conditions

                //Initializing and setting listener for repo
                respo = new MyRepository(this); //this is the listener interface

                repo.getAllContents();
            }
        }
    }

    //Interface method implemented
    @Override
    public void onDbUpdate(Content content) {
        //Do something with the data
    }
}

我将监听器传递给repo,我在监听器上调用onDbUpdate()方法,从而在接收器中获取响应。

如果它是一个活动/片段而不是广播接收器,我会简单地使用一个带有实时数据的viewModel作为observable,在我的活动中,我会观察viewmodel这样的更改

mViewModel.getAllContent().observe(this, new Observer<List<Content>>() {
   @Override
   public void onChanged(@Nullable final List<Content> contents) {
       // Do something
   }
});

我的方法是否正常或是否有一种明显更好的方法在BroadcastReceiver中实现这一目标?谢谢!!

android observer-pattern android-room android-mvvm
1个回答
1
投票

我相信你应该使用某种能够为你处理任务的经理。

Android目前有一个库Work Manager可以很好地处理这个问题。

使用WorkManager,您可以安排OneTimeWorkRequestPeriodicWorkRequest

另一个好处是你必须自己不必监听连接状态,因为你可以指定/配置这个以及传递给WorkManager的约束中的很多其他状态。

val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .setRequiresDeviceIdle(true)
            .setRequiresCharging(true)
            .build() 

是的,只要指定一个backOffCriteria,如果网络非常糟糕,它也可以处理重试。

val workRequest = OneTimeWorkRequest.Builder(RequestWorker::class.java)
            .setInputData(mapOf("record_id" to recordId).toWorkData())
            .setConstraints(constraints)
            .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.MINUTES)
            .build()

如果您对任务/工作的状态也感兴趣,可以通过调用LiveData<WorkStatus>来观察getStatusById(workId)

© www.soinside.com 2019 - 2024. All rights reserved.