创建一个被动的JobService

时间:2017-09-25 15:16:26

标签: android rx-java reactive-programming android-jobscheduler

我正在使用Firebase JobDispatcher(非常类似于常规JobService)创建JobService以在后台运行并检查服务器上的数据是否已更改(我无法使用推送)通知,因为我不拥有服务器)。

我想知道JobService是否可以在某个主题的帮助下被反应:基本上我将单个数据存储库注入我的app类中,然后启动JobService通过可在app类中订阅的主题发出新数据:

@Inject class DataRepo {
     internal val subject = PublishSubject.create<Data>()

     // the service should only be started when there are actually subscribers observing the subject
     val latestData: Observable<Data> = subject
             .doOnSubscribe { jobDispatcher.create(job) }
             .doOnDispose { jobDispatcher.cancel(job.tag) }
             .share()

     val job = JobDispatcher.newJobBuilder()......build()
}

class LoadDataService : JobService() {
    @Inject
    protected lateinit var dataRepo: DataRepo

    private var networkRequest: Disposable? = null

    override fun onCreate() {
        super.onCreate()
        component.inject(this)
    }

    override fun onStartJob(jobParams: JobParameters): Boolean {
        networkRequest = dataRepo.getNewestData()
                .subscribe({ newData ->
                    dataRepo.subject.onNext(newData)
                    jobFinished(jobParams, false)
                }, { error ->
                    jobFinished(jobParams, true)
                })

        // job hasn't finished yet. Work is still going on in the background
        return true
    }

    override fun onStopJob(params: JobParameters?): Boolean {
        networkRequest?.dispose()
        // job was cancelled before jobFinished could be called.
        // The job should be retried if possible
        return true
    }
}

class App {
    @Inject val dataRepo: DataRepo

    override fun onCreate() {
        dataRepo.latestData.subscribe(this::sendNotification)
    }
}

问题在于,首先,我的排放量永远不会到达App级的用户,其次不能保证设备能够唤醒足够长的时间以便所有用户完成他们的工作,因为系统可能会在JobService调用jobFinished()后释放唤醒锁定。

0 个答案:

没有答案