简体   繁体   English

Android:在哪里安排工作?

[英]Android: Where to schedule a job?

I'm using LiveData+Room+ViewModel to build a simple kotlin app. 我正在使用LiveData + Room + ViewModel来构建一个简单的kotlin应用程序。 The main activity (which presents a list) is getting the required data from a ViewModel which is getting the info from a database (the data is transformed before being consumed by the activity). 主要活动(显示列表)是从ViewModel获取所需数据,ViewModel从数据库获取信息(数据在被活动使用之前进行转换)。 Now, I need to allow the user to refresh the data through a swipe. 现在,我需要允许用户通过滑动刷新数据。 When that happens, the app should check if the current connection can be used for that and if it can't, then the app should schedule a job. 当发生这种情况时,应用程序应检查当前连接是否可用于该连接,如果不能,则应用程序应安排作业。

Currently, I'm delegating this work (check the current connection and the eventual job scheduling) to my ViewModel. 目前,我将此工作(检查当前连接和最终作业调度)委托给我的ViewModel。 It looks like this: 它看起来像这样:

fun tryToRefreshDataFromService(){
    //first, check if there's network
    //If there is, call web service and then update db
    //if no network, schedule a job and try to refresh from the database
    if(canGetDataFromNetwork()){
        Timber.d("With network access, getting data from web services")
        WebServiceAsyncTask(newsManager).execute()
    }
    else{
        //schedule job for refreshing
        //no network access, setting up job
        Timber.d("No network access, setting up job")
        scheduleJob()
    }
}

The activity will then be able to call the method from within a helper method (which handles the swiper refresh event): 然后,该活动将能够从辅助方法(处理swiper刷新事件)中调用该方法:

private fun recoverDataForTabs(swiper: SwipeRefreshLayout? = null){
    _swiper = swiper //for clearing
    _viewModel.tryToRefreshDataFromService()
}

However, it seems like this is really a bad idea because it seems like ViewModels shouldn't know anything about Android framework classes (and that ends up being required for this case). 然而, 看起来这真的是一个坏主意,因为看起来ViewModels似乎不应该知道任何关于Android框架类的东西(并且最终需要这种情况)。 So, does this mean that I should update my code so that the network checking + job scheduling is done from the activity? 那么,这是否意味着我应该更新我的代码,以便从活动中完成网络检查+作业调度?

Thanks 谢谢

You can inject framework-related objects into your ViewModels . 您可以将与框架相关的对象注入ViewModels For example: 例如:

class MyViewModel(val networkChecker: IMyNetworkChecker, val jobSetter: IMyJobSetter, ...) {

    fun tryToRefreshDataFromService(){
        if(networkChecker.canGetDataFromNetwork()){
            Timber.d("With network access, getting data from web services")
            WebServiceAsyncTask(newsManager).execute()
        }
        else{
            Timber.d("No network access, setting up job")
            jobSetter.scheduleJob()
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM