Skip to main content

Conditional navigation and single event LiveData


Conditional navigation is a little tricky when it comes to Navigation Architecture. There are plenty of nice articles and solutions about it, but I'm sharing the way I solve this important problem. So let's consider this use case:


If you don't put HomeFragment as a start destination, you will have some serious trouble with the fragment back stack and you would need to write the onBackPressDispatcher in every fragment. Therefore, don't do it.

There is also an easier step to do this directly in the OnlyActivity you have, and it's pretty nice too, but I've noticed that Google suggest the activities to be kept just for holding <fragment>s and nothing more. Otherwise it would violate the responsibility that the new Architecture Activity behaviour has (like checking from its' ViewModel user authentication etc).

So it's just fragments. A common problem you might face is when you use LiveData<T> the usual way for this case. I'm not handling the way google does it here, because that's already implemented in their documentation. So for instance, I'm just handling a boolean in this case (authenticated or not):

The problem
Now, if your login goes successful and you close the fragment by popping the back stack after the user authentication (findNavController.popBackStack()), the login screen would reappear. So what could have gone wrong? Well since you are just adding the LoginFragment to the back stack, the HomeFragment never gets closed, and so does its' attached ViewModel. When the HomeFragment is back on top, it start observing the LiveData<Boolean> again, only now, its' value is true because the ViewModel has been alive all the time, making it a never ending cycle.


You can fix this however with a small (but really dangerous) hack:

I wouldn't recommend this way, because it's really a hack and not an actual solution. Furthermore, it's not good code and sometimes happens that the second value might not emit at all because of the nature of LiveData.

Single events ftw:

Well, the best solution is to use a mix of an EventBus with LiveData. This would be a perfect duo for Fragment + ViewModel design when it comes to single events:

It doesn't really look complicated at all and it's pretty safe this way.

Note: Also notice to place LoginFragment as top level destination, otherwise when you would press the back button in your device, you would infinitely get inside the loop of popping up this fragment.
The actual conditions do not depend just from a boolean value. It's easier with states.

Now, what if the user doesn't have an account and needs to register. In this case, you would need to track the back stack. Login -> Register -> Confirmation. And backwards Confirmation -> Register -> Login. But there seems to be a problem with this case. If the registration is successful, you might want to log him directly from there without making him/her put login credentials again (this way would just need to press the back button until arrival to Login screen again). If you think about it, you might wanna pop the back stack twice, once for Confirmation Screen and once for Registration. But this would require a bunch of flags, navigation arguments between 2 fragments and a lot of hacks. However, navigation components do solve something really nicely. There is an option in which you can pop the back stack from one fragment until the desired fragment. This can be achieved just by just typing the desired destination in the ConfirmationFragment (in our case). So, we would want to pop the back stack until we arrive to HomeFragment (which will check authentication and do nothing because we are done with that part): findNavController().popBackStack(R.id.home_fragment, false)

And that's it. A small thing to notice is that Google's suggestion with states looks more complicated but it is more reliable as a solution. I was just handling the problem of single events with live data and showing a simpler way for conditional navigation.

Conclusion.


The navigation components might have complicated a little bit the conditional navigation. However for people who are willing to use single activity, this solution is pretty nice, I guess. If you have more than one activity, this would be a strong reason to keep it that way. A login/register flow and the base app could be achieved with 2 activities with less work, but anyways, I still think that having more than one Activity in your app is redundant.

Credits: Jose Alcérreca with his article about single events.
If you want to check Googles source for conditional navigation, here is the link.

Stavro Xhardha

Popular posts from this blog

Modularizing your Android app, breaking the monolith (Part 1)

Inspired by a Martin Fowlers post about Micro Frontends, I decided to break my monolithic app into a modular app. I tried to read a little more about breaking monolithic apps in Android, and as far as I got, I felt confident to share my experience with you. This will be some series of blog posts where we actually try to break a simple app into a modularized Android app.

Note: You should know that I am no expert in this, so if there are false statements or mistakes please feel free to criticize, for the sake of a better development. 

What do you benefit from this approach:
Well, people are moving pretty fast nowadays and delivery is required faster and faster. So, in order to achieve this, modularising Android apps is really necessary.You can share features across different apps. Independent teams and less problems per each.Conditional features update.Quicker debugging and fixing.A feature delay doesn't delay the whole app. As per writing tests, there is not too much difference about…

What I learned from Kotlin Flow API

I used to check the docs and just read a lot about flows but didn't implement anything until yesterday. However, the API tasted really cool (even though some operations are still in Experimental state).Prerequisites: If you don't know RxJava it's fine. But a RxJava recognizer would read this faster.Cold vs Hot streamsWell, I really struggled with this concept because it is a little bit tricky. The main difference between cold and hot happened to be pretty simple: Hot streams produce when you don't care while in cold streams, if you don't collect() (or RxJava-s equivalent subscribe()) the stream won't be activated at all. So, Flows are what we call cold streams. Removing the subscriber will not produce data at all, making the Flows one of the most sophisticated asynchronous stream API ever (in the JVM world). I tried to make a illustration of hot and cold streams: Since I mentioned the word asynchronous this implies that they do support coroutines also. Flows vs…

From Gson to Moshi, what I learned

There is no doubt that people are getting away from GSON and I agree with those reasons too. The only advantage GSON has over other parsing libraries is that it takes a really short amount of time to set up. Furthermore, the most important thing is that Moshi is embracing Kotlin support.

First let's implement the dependency:
implementation("com.squareup.moshi:moshi:1.8.0") It's not a struggle to migrate to Moshi. It's really Gson look-a-like. The only thing to do is annotate the object with @field:Json instead of @SerializedName (which is Gsons way for JS representation):

data class User( //GSON way @SerializedName("name") val name: String, @SerializedName("user_name") val userName: String, @SerializedName("last_name") val lastName: String, @SerializedName("email") val email: String ) data class User( //Moshi way @field:Json(name = "name") val name: String, @field:Json(name = "user_name…