app: buffer navigation events until collected

ViewModels requested navigation through a SharedFlow without replay, so
a request was silently dropped when no screen was collecting it. This
happens when an activity result arrives right after the activity was
recreated: the launcher delivers it before the screen's collector has
started. E.g. after a configuration change while picking an image to
patch, the patch dialog closed but the patching screen never opened.

Use a buffered Channel instead, so requests wait for the collector.

Assisted-by: Claude Opus 5.5
This commit is contained in:
topjohnwu
2026-10-24 13:01:45 -07:00
committed by John Wu
parent cbb813c41e
commit cbd8f32d90
@@ -6,13 +6,16 @@ import androidx.lifecycle.ViewModel
import com.topjohnwu.magisk.core.AppContext
import com.topjohnwu.magisk.core.ktx.toast
import com.topjohnwu.magisk.ui.navigation.Route
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
abstract class BaseViewModel : ViewModel() {
private val _navEvents = MutableSharedFlow<Route>(extraBufferCapacity = 1)
val navEvents: SharedFlow<Route> = _navEvents
// Keep requests until the UI collects them: one can arrive before the screen's collector
// has (re)started, e.g. from an activity result delivered right after a recreation
private val _navEvents = Channel<Route>(Channel.BUFFERED)
val navEvents: Flow<Route> = _navEvents.receiveAsFlow()
fun showToast(@StringRes resId: Int) {
AppContext.toast(resId, Toast.LENGTH_SHORT)
@@ -23,6 +26,6 @@ abstract class BaseViewModel : ViewModel() {
}
fun navigateTo(route: Route) {
_navEvents.tryEmit(route)
_navEvents.trySend(route)
}
}