Converting a pure view model to a reactive one

Terrick Mansur
2 min readNov 20, 2020

--

Writing a pure view model makes it very easy to test and understand. But writing a pure view model reactively makes for better code.

Photo by Steve Johnson on Unsplash

In my last article, we converted an impure view model into a pure one. At the end of the article, we saw that the mutability of one of the properties in the view model property is not ideal. In this article, I will fix this issue by converting this pure view model into a reactive one.

Let’s take a look at the view model again.

The name property in the view model is mutable, and it needs to be since this needs to be updated when we update the view model with the NameService.Response. However the issue with name being mutable is that anyone that has access to our view model can change its value. Here is an example of a mistake someone might do.

We can easily fix this by marking the set as private by declaring it like so private(set) var name = "". But we are still leaving room internally to make mistakes like so.

The reason there is still room for mistake in this setup is because name is only the storage of the result of the transformation of NameService.Response to name.

When you write FRP code, you never want to store any state. What you want isnameto be the actual transformation. Below is an example of how you could write this in a functional way.

name is now the transformation of NameService.Responseto name, NOT the storage of the resulted transformation.

Where reactive programming comes to play is with events. For that, we would need to take a signal of the type Service.Responsein the initializer and have name be a signal that is the mapping/transformation of the Service.Response signal into the namesignal. Let's look at the example below.

In this example again we can see again that name is not the storage of the resulted transformation, but the actual transformation of the response. The only difference in this example is that it is reactive.

Thank you for reading

If you liked this article please follow me and show your support with a clap. If you want to read my other articles, below is a list.

My articles:
1. The missing piece of MVVM

2. What are Pure Functions?

3. Pure functions? What about Pure view models?

Get in touch:

--

--

No responses yet