82 lines
2.5 KiB
Kotlin
Raw Normal View History

2020-08-18 06:31:15 -07:00
package com.topjohnwu.magisk.arch
import android.Manifest.permission.*
import android.annotation.SuppressLint
import android.os.Bundle
2020-07-12 14:37:07 -07:00
import androidx.databinding.PropertyChangeRegistry
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.navigation.NavDirections
import com.topjohnwu.magisk.R
2021-09-01 01:11:57 -07:00
import com.topjohnwu.magisk.databinding.ObservableHost
2021-05-09 20:45:53 -07:00
import com.topjohnwu.magisk.events.BackPressEvent
2023-04-03 17:46:49 -07:00
import com.topjohnwu.magisk.events.DialogBuilder
import com.topjohnwu.magisk.events.DialogEvent
2021-05-09 20:45:53 -07:00
import com.topjohnwu.magisk.events.NavigationEvent
import com.topjohnwu.magisk.events.PermissionEvent
import com.topjohnwu.magisk.events.SnackbarEvent
abstract class BaseViewModel : ViewModel(), ObservableHost {
2020-07-12 14:37:07 -07:00
override var callbacks: PropertyChangeRegistry? = null
private val _viewEvents = MutableLiveData<ViewEvent>()
2022-06-10 04:12:31 -07:00
val viewEvents: LiveData<ViewEvent> get() = _viewEvents
open fun onSaveState(state: Bundle) {}
open fun onRestoreState(state: Bundle) {}
open fun onNetworkChanged(network: Boolean) {}
fun withPermission(permission: String, callback: (Boolean) -> Unit) {
PermissionEvent(permission, callback).publish()
2020-07-08 01:26:45 -07:00
}
2021-11-05 15:53:34 -07:00
inline fun withExternalRW(crossinline callback: () -> Unit) {
withPermission(WRITE_EXTERNAL_STORAGE) {
if (!it) {
SnackbarEvent(R.string.external_rw_permission_denied).publish()
} else {
callback()
}
}
}
@SuppressLint("InlinedApi")
inline fun withInstallPermission(crossinline callback: () -> Unit) {
withPermission(REQUEST_INSTALL_PACKAGES) {
if (!it) {
SnackbarEvent(R.string.install_unknown_denied).publish()
} else {
callback()
}
}
}
@SuppressLint("InlinedApi")
inline fun withPostNotificationPermission(crossinline callback: () -> Unit) {
withPermission(POST_NOTIFICATIONS) {
if (!it) {
SnackbarEvent(R.string.post_notifications_denied).publish()
} else {
callback()
}
}
}
fun back() = BackPressEvent().publish()
2023-04-03 17:46:49 -07:00
fun ViewEvent.publish() {
_viewEvents.postValue(this)
}
2023-04-03 17:46:49 -07:00
fun DialogBuilder.show() {
DialogEvent(this).publish()
2020-07-10 04:19:18 -07:00
}
fun NavDirections.navigate(pop: Boolean = false) {
_viewEvents.postValue(NavigationEvent(this, pop))
}
}