Created
June 30, 2022 13:47
-
-
Save Astroa7m/2cdb174fe3491735569053c25d5c49e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainScreenViewModel ( | |
application: Application | |
) : ViewModel() { | |
private val preferencesManager = PreferencesManager(application) | |
val imageCategoryIndex = preferencesManager.imageCategoryPref | |
private var workManager = WorkManager.getInstance(application) | |
init { | |
imageCategoryIndex.onEach { | |
setWork(it) | |
}.launchIn(viewModelScope) | |
} | |
fun setCategory(categoryIndex: Int) { | |
viewModelScope.launch { | |
preferencesManager.setImageCategory(categoryIndex) | |
} | |
} | |
private fun setWork(categoryIndex: Int) { | |
val inputData = Data.Builder().putInt(CURRENT_CATEGORY, categoryIndex).build() | |
val constraints = Constraints.Builder() | |
.setRequiredNetworkType(NetworkType.CONNECTED) | |
.build() | |
val work = PeriodicWorkRequestBuilder<RemoteImageWorker>(15, TimeUnit.MINUTES) | |
.setConstraints(constraints) | |
.setInputData(inputData) | |
.build() | |
workManager.enqueue(work) | |
} | |
} | |
class MainScreenViewModelFactory(private val application: Application) : ViewModelProvider.Factory { | |
override fun <T : ViewModel> create(modelClass: Class<T>): T { | |
return if (modelClass.isAssignableFrom(MainScreenViewModel::class.java)) { | |
MainScreenViewModel(application) as T | |
} else { | |
throw IllegalArgumentException("Unknown ViewModel class") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment