Tusky-App-Android/app/src/main/java/com/keylesspalace/tusky/components/domainblocks/DomainBlocksViewModel.kt

94 lines
3.0 KiB
Kotlin
Raw Normal View History

package com.keylesspalace.tusky.components.domainblocks
2023-07-04 19:30:57 +02:00
import android.view.View
import androidx.annotation.StringRes
2023-07-04 19:30:57 +02:00
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import at.connyduck.calladapter.networkresult.fold
import com.keylesspalace.tusky.R
2023-07-04 19:30:57 +02:00
import com.keylesspalace.tusky.network.MastodonApi
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
class DomainBlocksViewModel @Inject constructor(
2023-07-04 19:30:57 +02:00
private val api: MastodonApi
) : ViewModel() {
val domains: MutableList<String> = mutableListOf()
val uiEvents = MutableSharedFlow<SnackbarEvent>()
2023-07-04 19:30:57 +02:00
var nextKey: String? = null
var currentSource: DomainBlocksPagingSource? = null
2023-07-04 19:30:57 +02:00
@OptIn(ExperimentalPagingApi::class)
val pager = Pager(
config = PagingConfig(pageSize = 20),
remoteMediator = DomainBlocksRemoteMediator(api, this),
2023-07-04 19:30:57 +02:00
pagingSourceFactory = {
DomainBlocksPagingSource(
2023-07-04 19:30:57 +02:00
viewModel = this
).also { source ->
currentSource = source
}
}
).flow.cachedIn(viewModelScope)
fun block(domain: String) {
2023-07-04 19:30:57 +02:00
viewModelScope.launch {
api.blockDomain(domain).fold({
domains.add(domain)
currentSource?.invalidate()
}, { e ->
uiEvents.emit(
SnackbarEvent(
message = R.string.error_blocking_domain,
domain = domain,
throwable = e,
actionText = R.string.action_retry,
action = { block(domain) }
)
)
2023-07-04 19:30:57 +02:00
})
}
}
fun unblock(domain: String) {
2023-07-04 19:30:57 +02:00
viewModelScope.launch {
api.unblockDomain(domain).fold({
domains.remove(domain)
currentSource?.invalidate()
uiEvents.emit(
SnackbarEvent(
message = R.string.confirmation_domain_unmuted,
domain = domain,
throwable = null,
actionText = R.string.action_undo,
action = { block(domain) }
)
)
2023-07-04 19:30:57 +02:00
}, { e ->
uiEvents.emit(
SnackbarEvent(
message = R.string.error_unblocking_domain,
domain = domain,
throwable = e,
actionText = R.string.action_retry,
action = { unblock(domain) }
)
)
2023-07-04 19:30:57 +02:00
})
}
}
}
class SnackbarEvent(
@StringRes val message: Int,
val domain: String,
val throwable: Throwable?,
@StringRes val actionText: Int,
val action: (View) -> Unit
)