Android MVP存储库模式的互联网检查

时间:2018-12-30 01:14:21

标签: java android observable rx-java

我正在遵循MVP存储库模式。我想向用户显示数据列表,但我的想法是遵循存储库模式。这意味着我有一个与主持人交谈的存储库。此存储库与2个数据源进行通信-存储和RemoteAPI。

首先,存储库为演示者提供了存储库中的数据列表,如果存在互联网以获取最新数据列表并将其存储在存储库中,则并行调用RemoteAPI,并将其返回给演示者。

此外,当没有互联网时,我需要向用户显示没有互联网以及存储中的数据。

这是我在存储库中的代码-

return Observable.create<ArrayList<Data>> { subscriber ->

            val dataFromCache = storage?.dataFromCache()
            val fromCache = dataFromCache != null && dataFromCache.isNotEmpty()

            if (fromCache) {
                subscriber.onNext(dataFromCache)
            }

            if (Utils.isInternetOn(context)) {

                // attempt to update from online source
                try {

                    remoteApi?.getDataFromAPI()
                            ?.subscribeOn(Schedulers.io())
                            ?.observeOn(AndroidSchedulers.mainThread())
                            ?.subscribe(object : Subscriber<ArrayList<Data>>() {

                                override fun onCompleted() {
                                    subscriber.onCompleted()
                                }

                                override fun onError(e: Throwable) {

                                    if (fromCache) {
                                        subscriber.onCompleted()
                                    } else {
                                        subscriber.onError(e)
                                    }
                                }

                                override fun onNext(response: ArrayList<Data>) {
                                    // notify subscriber
                                    subscriber.onNext(response)
                                    // write to cache
                                    storage?.storeData(response)
                                    subscriber.onCompleted()
                                }
                            })

                } catch (e: Exception) {

                    // If we used the cache as fallback, this is not an issue
                    if (fromCache) {
                        subscriber.onCompleted()
                    } else {
                        subscriber.onError(e)
                    }
                }
            } else {
                subscriber.onError(Exception("NO_INTERNET"))
            }
        }

但是问题是,当没有互联网时,他转到代码的其他部分并抛出NO_INTERNET。如何同时从存储和异常NO_INTERNET中获取数据?

0 个答案:

没有答案