adrielcafe / voyager

🛸 A pragmatic navigation library for Jetpack Compose
https://voyager.adriel.cafe
MIT License
2.27k stars 109 forks source link

Navigation from ScreeModel #385

Open GtechGovind opened 1 month ago

GtechGovind commented 1 month ago

In my current scenario, I'm seeking a solution to navigate from a ScreenModel to another screen. Regrettably, I haven't discovered a suitable method to accomplish this yet. Could you please provide guidance or suggestions on how to enable this navigation? Any assistance would be greatly appreciated. Thank you.

akardas16 commented 1 month ago

you can achieve it with callbacks easily (kotlin callbacks)

assume below function is in your ScreenModel

 suspend fun loginUser(result:(data: UserResponse?, error: String?) -> Unit){ 
        repository.loginUser(model){response, error ->
            response?.let {
                  result(it, null)
            }
            error?.let {
                Log.i("error", "loginUser Error: $it")
               result(null, it)
            }
        }
    }

you can call it in your screen like below

  screenModel.loginUser{data, error ->
          response?.let{
               //navigate another screen in here
       }
 }
nvkleban commented 1 month ago

There are two main approaches that I know:

  1. With UiState - set some flag that indicates you need to navigate somewhere, then consume it by unsetting it screenmodel.navigetedToSomeScreen().
  2. With one time effects - use some kind of Channel that exposes events as Flow