Tag Archives: article

Unidirectional data flow in practice

Recently I made a small test project, where I could try out the unidirectional data flow in swift, suggested by Benjamin Encz. You can watch his talk on Realm: https://realm.io/news/benji-encz-unidirectional-data-flow-swift/ What I was interested in, is how can I integrate it into a complex project where I have to perform async tasks. I found out that there is no support for async tasks yet, but you can still achieve it with a workaround. However I would be glad to see it integrated.

The workaround is that in your controller you don’t start actions directly. You implement a service layer instead, and you perform async tasks through that (actually I prefer performing every tasks through the service layer). When the task is done, you create the action inside the service, and send it to the store. So for example if you have to fetch some data from the server, you call the API from the service, and when you get the data you create the corresponding action. The data process part (JSON parsing) can happen either inside the service or the reducer. I’m not sure which option is the better approach.

The only downside is that you have to make sure you return to the main thread. Anyway the profit you gain using this library exceeds this little inconvenience: you have the current state in flows everywhere in the app, and you don’t have to pass it from one controller to another manually. Also you have fresh data everywhere in the app.