e-ntfy-android/app/src/main/java/io/heckel/ntfy/ui/SubscriptionsViewModel.kt

36 lines
1.2 KiB
Kotlin
Raw Normal View History

2021-10-28 05:04:14 +02:00
package io.heckel.ntfy.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
2021-10-30 03:13:58 +02:00
import androidx.lifecycle.viewModelScope
import io.heckel.ntfy.data.*
2021-10-30 03:13:58 +02:00
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.collections.List
2021-10-30 03:13:58 +02:00
class SubscriptionsViewModel(private val repository: Repository) : ViewModel() {
fun list(): LiveData<List<Subscription>> {
return repository.list()
}
2021-10-30 03:13:58 +02:00
fun add(topic: Subscription) = viewModelScope.launch(Dispatchers.IO) {
repository.add(topic)
}
2021-10-30 03:13:58 +02:00
fun remove(topic: Subscription) = viewModelScope.launch(Dispatchers.IO) {
repository.remove(topic)
}
}
2021-10-30 03:13:58 +02:00
class SubscriptionsViewModelFactory(private val repository: Repository) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>) =
with(modelClass){
when {
2021-10-30 03:13:58 +02:00
isAssignableFrom(SubscriptionsViewModel::class.java) -> SubscriptionsViewModel(repository) as T
else -> throw IllegalArgumentException("Unknown viewModel class $modelClass")
}
}
}