Hello all! I'm trying to show an Android Toast on...
# ballast
a
Hello all! I'm trying to show an Android Toast on a Jetpack Compose app after I have processed an Input from an InputHandler. Here's the code on the InputHandler that posts the Event:
Copy code
class 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:
Copy code
@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:
Copy code
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?
c
You can customize the Dispatchers used for processing Inputs, Events, SideJobs, and Interceptors, but they all run on
Dispatchers.Default
by default, Try adding this to your `BallastViewModelConfiguration.Builder`:
Copy code
builder
.dispatchers(
        inputsDispatcher = Dispatchers.Default,
        eventsDispatcher = Dispatchers.Main,
        sideJobsDispatcher = Dispatchers.Default,
        interceptorDispatcher = Dispatchers.Default,
    )
a
Ah - I see. That worked - Thanks!