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

52 lines
2 KiB
Kotlin
Raw Normal View History

2021-10-28 05:04:14 +02:00
package io.heckel.ntfy.ui
2021-12-30 14:23:47 +01:00
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
2021-10-30 03:13:58 +02:00
import androidx.lifecycle.viewModelScope
2022-01-18 20:28:48 +01:00
import io.heckel.ntfy.db.*
2021-12-30 14:23:47 +01:00
import io.heckel.ntfy.up.Distributor
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.getSubscriptionsLiveData()
}
fun listIdsWithInstantStatus(): LiveData<Set<Pair<Long, Boolean>>> {
return repository.getSubscriptionIdsWithInstantStatusLiveData()
2021-11-14 01:26:37 +01:00
}
2021-10-31 20:19:25 +01:00
fun add(subscription: Subscription) = viewModelScope.launch(Dispatchers.IO) {
repository.addSubscription(subscription)
}
2021-12-30 14:23:47 +01:00
fun remove(context: Context, subscriptionId: Long) = viewModelScope.launch(Dispatchers.IO) {
val subscription = repository.getSubscription(subscriptionId) ?: return@launch
if (subscription.upAppId != null && subscription.upConnectorToken != null) {
val distributor = Distributor(context)
distributor.sendUnregistered(subscription.upAppId, subscription.upConnectorToken)
}
repository.removeAllNotifications(subscriptionId)
2021-10-31 20:19:25 +01:00
repository.removeSubscription(subscriptionId)
}
suspend fun get(baseUrl: String, topic: String): Subscription? {
return repository.getSubscription(baseUrl, 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")
}
}
}