Adrian
09/08/2023, 4:36 AMclass SomeFeatureInputHandler() : InputHandler<SomeFeatureContract.Inputs, SomeFeatureContract.Events, SomeFeatureContract.State> {
override suspend fun InputHandlerScope<SomeFeatureContract.Inputs, SomeFeatureContract.Events, SomeFeatureContract.State>.handleInput(
input: SomeFeatureContract.Inputs
) = when (input) {
....
SomeFeatureContract.Inputs.saveButtonClicked -> {
...
postEvent(SomeFeatureContract.Events.ShowError("Error during Save"))
}
}
Here's the UI code that tries to handle the Event and launch a Toast:
@Composable
fun ButtonsScreen(
navController: NavController,
viewModel: SomeFeatureViewModel = getViewModel(),
onClick: () -> Unit
) {
val eventHandler = SomeFeatureEventHandler(LocalContext.current)
....
LaunchedEffect(viewModel, eventHandler) {
viewModel.attachEventHandler(this, eventHandler)
}
.....
}
=========================================================
class SomeFeatureEventHandler(private val context: Context) :
EventHandler<SomeFeature.Inputs, SomeFeatureContract.Events, SomeFeaturesContract.State> {
override suspend fun EventHandlerScope<SomeFeatureContract.Inputs, SomeFeatureContract.Events, SomeFeatureContract.State>.handleEvent(
event: SomeFeatureContract.Events
) {
when (event) {
is SomeFeatureContract.Events.ShowError -> {
Toast.makeText(context, event.errorMessage, Toast.LENGTH_LONG).show()
}
}
}
}
When I run the above, the SomeFeatureEventHandler
handles the Event but when it tries to launch the Toast I get the following error:
java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
Error above probably indicates that we are trying to initiate a Toast on an non-UI thread. So what's the proper way in Ballast to handle this?Casey Brooks
09/08/2023, 2:38 PMDispatchers.Default
by default,
Try adding this to your `BallastViewModelConfiguration.Builder`:
builder
.dispatchers(
inputsDispatcher = Dispatchers.Default,
eventsDispatcher = Dispatchers.Main,
sideJobsDispatcher = Dispatchers.Default,
interceptorDispatcher = Dispatchers.Default,
)
Adrian
09/08/2023, 3:57 PM