ReactiveX in Android with an example – RxJava

Reading Time: 5 minutes

What is Reactive Programming?

Reactive programming is programming with asynchronous data streams. It enables to create streams of anything – events, fails, variables, messages and etc. By using reactive programming in your application, you are able to create streams which you can then perform actions while the data emitted by those created streams.

Observer Pattern

The observer pattern is a software design pattern which defines a one-to-many relationship between objects. It means if the value/state of the observed object is changed/modified, the other objects which are observing are getting notified and updated.

ReactiveX

ReactiveX is a polyglot implementation of reactive programming which extends observer pattern and provides a bunch of data manipulation operators, threading abilities.

RxJava

RxJava is the JVM implementation of ReactiveX.

  • Observable – is a stream which emits the data
  • Observer – receives the emitted data from the observable
    • onSubscribe() – called when subscription is made
    • onNext() – called each time observable emits
    • onError() – called when an error occurs
    • onComplete() – called when the observable completes the emission of all items
  • Subscription – when the observer subscribes to observable to receive the emitted data. An observable can be subscribed by many observers
  • Scheduler – defines the thread where the observable emits and the observer receives it (for instance: background, UI thread)
    • subscribeOn(Schedulers.io())
    • observeOn(AndroidSchedulers.mainThread())
  • Operators – enable manipulation of the streamed data before the observer receives it
    • map()
    • flatMap()
    • concatMap() etc.

Example usage on Android

Tools, libraries, services used in the example:

  • Libraries:
    • ButterKnife – simplifying binding for android views
    • RxJava, RxAndroid – for reactive libraries
    • Retrofit2 – for network calls
  • Fake online rest API:
  • Java object generator from JSON file

What we want to achieve is to fetch users from 1. show in RecyclerView and load todo list to show the number of todos in the same RecyclerView without blocking the UI.

Here we define our endpoints. Retrofit2 supports return type of RxJava Observable for network calls.

    @GET("/users")
    Observable<List<User>> getUsers();

    @GET("/users/{id}/todos")
    Observable<List<Todo>> getTodosByUserID(@Path("id") int id);

    @GET("/todos")
    Observable<List<Todo>> getTodos();

Let’s fetch users:

  • .getUsers – returns observable of a list of users
  • .subscribeOn(Schedulers.io()) – make getUser() performs on background thread
  • .observeOn(AndroidSchedulers.mainThread()) – we switch to UI thread
  • flatMap – we set data to RecyclerView and return Observable user list which will be needed in fetching todo list
    private Observable<User> getUsersObservable() {
        return ServicesProvider.getDummyApi()
                .getUsers()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap((Function<List<User>, ObservableSource<User>>) users -> {
                    adapterRV.setData(users);
                    return Observable.fromIterable(users);
                });
    }

Now, fetch todo list of users using the 2nd endpoint.

Since we are not going to make another call, we don’t need Observable type in return of this method. So, here we use map() instead of flatMap() and we return User type.

    private Observable<User> getTodoListByUserId(User user) {
        return ServicesProvider.getDummyApi()
                .getTodosByUserID(user.getId())
                .subscribeOn(Schedulers.io())
                .map(todoList -> {
                    sleep();
                    user.setTodoList(todoList);
                    return user;
                });
    }

Now, fetch todo list of users using the 3rd endpoint.

The difference to the 2nd endpoint is that this returns a list of todos for all users. Here we can see the usage of filter() operator.

    private Observable<User> getAllTodo(User user) {
        return ServicesProvider.getDummyApi()
                .getTodos()
                .subscribeOn(Schedulers.io())
                .flatMapIterable((Function<List<Todo>, Iterable<Todo>>) todoList -> todoList)
                .filter(todo -> todo.getUserId().equals(user.getId()) &amp;&amp; todo.getCompleted())
                .toList().toObservable()
                .map(todoList -> {
                    sleep();
                    user.setTodoList(todoList);
                    return user;
                });
    }
  • .flatMapIterable() – is used to convert Observable<List<T>> to Observable<T> which is needed for filter each item in list
  • .filter() – we filter todos to get each user’s completed todo list
  • .toList().toObservable() – for converting back to Observable<List<T>>
  • .map() – we set filtered list to user object which will be used in next code snippet

Now, the last step, we call the methods:

        getUsersObservable()
                .subscribeOn(Schedulers.io())
                .concatMap((Function<User, ObservableSource<User>>) this::getTodoListByUserId) // operator can be concatMap()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposables.add(d);
                    }

                    @Override
                    public void onNext(User user) {
                        adapterRV.updateData(user);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.d(TAG, "completed!");
                    }
                });
  • subscribeOn() – makes the next operator performed on background
  • concatMap() – here we call one of our methods getTodoListByUserId() or getAllTodo()
  • .observeOn(), .subscribe() – every time the user’s todo list is fetched from api in background thread, it emits the data and triggers onNext() so we update RecyclerView in UI thread
  • Left
    • getTodoListByUserId()
    • flatMap()
  • Right
    • concatMap()
    • getAllTodo() – filter usage

Difference between flatMap and concatMap is that the former is done in an arbitrary order but the latter preserves the order

Disposable

When an observer subscribes to an observable, a disposable object is provided in onSubscribe() method so it can later be used to terminate the background process to avoid it returning from callback to a dead activity.

private CompositeDisposable disposables = new CompositeDisposable();

observableobject.subscribe(new Observer() {
    @Override
    public void onSubscribe(Disposable d) {
        disposables.add(d);
    }

@Override
protected void onDestroy() {
    super.onDestroy();
    disposables.dispose();
}

Summary

In this post, I tried to give brief information about reactive programming, observer pattern, ReactiveX library and a simple example on android.

Why should you use RxJava in your projects?

  • less boilerplate code
  • easy thread management
  • thread-safety
  • easy error handling

Gitlab Repository

Example sourcecode: https://gitlab.com/47northlabs/public/android-rxjava

Links

N47 Playground: Be up-to-date with the latest technologies and don’t waste resources

Reading Time: 4 minutes

Our company is established from techies 👨🏼‍💻 for techies 👩🏼‍💻 and therefore we love ♥️ technology. This passion brings us always forward 🏃🏿‍♂️to learn the latest technologies and keeps us hungry for solving also our own issues with some cool 😎 and fun-making technologies 🤩.

To be an attractive technology focussed employer

A simple agency lifestyle with working on preselected technologies from clients for a long period can (and will) be boring 😕 for every technology enthusiast. 🧝‍♂️ To keep everybody on a high level of motivation 💪🏻, we think a company has to develop his own spirit and in our case, these are solutions with the latest frameworks, technologies, languages, gadgets,…

How not to waste time and money?

But in agency life is hard to reserve some resources 💰 just for a playground 🎮 or disposable products. Therefore you will need a setup, where you transform the need for discovering 🔍 new areas and costs 💰 into an intelligent investigation 🤑. By this frame, we decided, that every outcome of our playground should result as a standalone solution either for our company or as a resealable product. By doing this, our new unit LABS 🧪 and researchers 👩🏼‍🔬👨🏻‍🔬 are born.

How our unit LABS are working?

First steps into the new area!

In LABS 🧪 we get in the first touch with latest technologies and for sure we will face with all the issues ☄️, problems 👮🏻‍♂️, bugs 🐞, challenges 👨🏼‍🎤 and we learn a lot about the bad sides of new technologies. If we overcome all this problems and troubles 🧗🏿‍♂️, we move this new technology from our #playground to #weStandFor, which means that we are that good in that new technology and faced and solved all issues, that can occur. Now we are ready and stand for the latest technologies! 🏆🥇
Thus, the outcome of an e.g. 3 months focus in LABS is a great knowledge about a brand new technology and a gorgeous new product or solution. I think we can be proud of both! 👏🏻👏🏻

The movement of technology from #playground to #weStandFor. Every stack has his own topic leader, so don’t miss changes and updates.

To manage this pipeline from playground 🎮 to the output ✅ we set up a backlog with great projects. Everybody in our company is free to add some projects to our backlog and come up with ideas 💡. In this accelerator program, we decide the sustainability and the potential of this suggested project 📊 and evaluate the sexiness of the technologies 🙀. If we all agree with this internal pitch we plan and start having work and fun! 🥳

What does this mean for our partners and clients?

With our LABS unit, we can offer you an overview and solutions by using the latest technologies 👩🏼‍💻, which can give you more security 🔐, to be an early adaptor 🥇 on your specific market or even save money 💵!

What does this mean for our techies and applicants?

At N47 you have great development possibilities 📈 and learn always new technologies. You are not stuck into a technology for years 🤷🏼‍♂️, that you miss new things. In our LABS unit and also with our Hackdayz you have the opportunity to develop awesome products and contribute a great environment for yourself and your teammates. Join us today in Zurich 🇨🇭, Konstanz 🇩🇪 or Skopje 🇲🇰.

WeAreDevelopers World Congress 2019 – Expectations

Reading Time: 3 minutes

Why this one?

I’m a mobile developer. In specific an iOS developer. So guess what, I love writing code either in Swift or Objective-C for Apple devices. When searching for a conference to attend in 2019 I rather had the WWDC in mind. There is one drawback, however you need some serious money and luck to get there. But in general, there are plenty of other good iOS conferences to attend (NSConf, CocoaConf, …, you name it!). 

For an overview and a brief description of iOS conferences in 2019 I found this page from Hacking with Swift very informative.

There is a very nice overview diagram of iOS conferences depending on your location and/or budget in an old post (2017) at raywenderlich.com. Although outdated, most of these conferences will also happen in 2019 and pricing and location rarely (dramatically) change.

Wait, but the post is about your expectations for the World Congress 2019 in Berlin. So what happened?

Ok, let’s get to this. When searching for iOS conferences in 2019, this conference somehow slipped into the search results. And it did so because Steve Wozniak was speaking there. Well, which iOS/Mac developer wouldn’t want to see and hear the legendary Steve Wozniak, right?

Once on the WeAreDevelopers homepage I realised that Steve Wozniak was giving a talk there a year earlier. So, 2018 in Vienna. Furthermore, this conference isn’t iOS or even mobile specific. That’s another drawback. Anyway, once on the page I skimmed through this year’s speakers. Here are some of them:

  • Rasmus Lerdorf – Inventor of PHP
  • Håkon Wium Lie – Inventor of CSS
  • Andreas M. Antonopoulos – Author, Mastering Bitcoin

Well, maybe Steve Wozniak is not there, but there are a lot of high quality people from IT in general. People who had and have a tremendous impact on millions of developers out there. One can argue about the weaknesses and strengths of PHP, CSS, Bitcoin. But one is for sure. With all downsides, these technologies are used and working on a daily basis. Furthermore, there are vibrant communities behind them.

Ok then. I’am going because I would like to see a broader picture of tech then just a little piece of it.

Btw there are mobile related talks anyway.

Expectations (TL;DR)

  • Experience some good talks from people with impact
  • Get a feeling where we’re headed in the future
  • Maybe see some demos/MVPs on AR/VR, Robotics
  • Get answers where bitcoin and blockchain are going and what the state of disruption is
  • Socialising

FrontCon 2019 in Riga, Latvia

Reading Time: 3 minutes

Only a few weeks left until I go to my first tech conference this year. Travelling means for me learning something new. And I like learning. Especially the immersion in a foreign culture and the contact to people of other countries makes me happy.

It’s always time to grow beyond yourself. 🤓

BUT why visit Riga just for a conference? Riga is a beautiful city on the Baltic Sea and the capital of Latvia. Latvia is a small country with the neighbours: Russia, Lithuania, Estonia and the sea. AND it’s a childhood dream of me to get to know this city. 😍

The dream was created by an old computer game named “The Patrician”. It’s a historical trading simulation computer game and my brothers and I loved it. We lost a lot of hours to play it instead of finding a way to hack it. 😅
For this dream, I will take some extra private days to visit Riga and the Country as well. 😇

Preparation

The most important preparation such as flight, hotel, workshop and conference are completed.

Furthermore, I also plan to visit some of the famous Latvian palaces and the Medieval Castle of Riga. I also need some tips for the evenings: restaurants and sightseeings from you. Feel free to share them in the comments. 😊

Some facts about the conference

There are four workshops available on the first day:

  • Serverless apps development for frontend developers
  • Vue state management with vuex
  • From Zero to App: A React Workshop
  • Advanced React Workshop

I chose the workshop with VueJS of course 😏 and I’m really happy to see that I can visit most of the talks in the following days. There are some interesting speeches like “Building resilient frontend architecture”, “AAA 3D graphics” and secure talks and server-less frontend development. Click here for the full list of tracks.

My expectations

Above all, I’m open to events to learn new things. Therefore, I have no great expectations in advance. So I’m looking forward to the

  • VueJS & Reacts parts
  • Visit the speakers from Wix, N26 and SumUp

I’m particularly curious about the open spaces between the speeches. I will be glad to have some great talks with the guys. 🤩

For my private trips:

That’s all for now

to be continued…

My experience with remote interviews

Reading Time: 3 minutes

As a developer, who is recruiting, you always try to find the best fit for the available position in your company. Your goal is to find someone who will fit in the team and make the whole company go forward.

Hi guys, my name is Youssef Idelhoussain, and I’m a Senior Front-end Developer @N47. I remember the day when I got the first task to interview a developer for an open position, during that day I was so stressed as if I was the one who is being interviewed, googling and trying to find the best way to interview somebody by asking around for expert advice. The hilarious thing I hadn’t even eaten all over the day. But at one moment I realized that I should just be myself, and try to find a new teammate. For me, soft skills were always the number one because being a developer is not just about:

Maybe that was in the nineties, but nowadays it’s more like:

More meetings, conferences, talking with people, understanding your teammates, communicating and explaining your point better.

All of the mentioned above is very important, but we should not forget about the most important skills, and that are the practical ones needed for the position. If you say that you are a Senior Front-end Developer, you should at least know the basics of JavaScript, HTML, and CSS… And to test all of these I think I found the best tool, and that’s CodeInterview.

The Tool: Code Interview 👨‍💻💬

What the tool does is very simple: pair programming for interviews, so that you can test the practical skills and the interviewees, test their response to some difficult tasks and test how they manage their stress during solving some tasks.

Pros

  • Live coding
  • The tool supports many languages
  • Live compiling
  • Video & Audio calls
  • Save & Load Snippets
  • Add notes

Cons

  • Still in Demo Mode
  • Paid service

Conclusion

CodeInterview introduces a new way of interviewing in our newly developed society, it has more pros than cons, for me, it gets an A.

I really recommend it to any single company out there, go on and try it out and feel free to comment your thoughts below.

Facial recognition technology and its effect on health insurance companies

Reading Time: 6 minutes

When I was young, I used to make fun of people who believe that other people can read their future out of hand, and I still make fun of them, but during last year I figured out that with the help of technology, it is now easy to read people’s hidden presence.

As an iPhone user, yesterday, while I was unlocking my mobile using facial recognition, I took a moment of thinking and I found how far we have reached using this technology within all business fields especially in health insurance companies. So as being one of 250,000,000 annual customer of apple (250,000,000 average of iPhone devices sold per year), I became really surprised and fascinated about facial recognition technology to the point I opened up my mouth.

Off late, apparently, that our face has not just become as a way of recognizing ourselves. In the era of computer, which sees more than we do by far and learns faster than us by far. Most important, it sees some really personal secrets. For a second my mind got frozen from happiness as finally I can imagine what the real emotion for Mona Lisa was 😀, RIP da Vinci.

Yeah…. she looks neutral!

In such an amazing computer simulation experiment at Stanford University, two researchers made the computer study more than 35,000 photos from self-identified and heterosexual people from public dating sites and after training the computer, the algorithm was able to correctly differentiate gay and heterosexual men with an accuracy reaching 81% of and 71% accuracy for women. Just from the face, the device (artificial intelligence) becomes able to differentiate, identify and predict the sample based on sexual orientation. At the end of the research, the researches wrote “our findings expose a threat to the privacy of men and women”. Moreover, if you show the device 5 pictures of the same person, its recognition accuracy jumps up to 91% and this just through the face. Such a surprisingly percentage as human mind can only reach 60% of recognition with the same number of photos. From this study, we can see, there is a direct positive relationship between increasing the sample size and level of recognition accuracy.

So from what has been stated above, we can reach a conclusion that by increasing sample size, the accuracy level increases. We can prove our conclusion by the result declared in China. This development of technology is now able to recognize the citizens in a heavily populated country like China in less than 3 seconds. Out of 1,400,000,000 citizens (sample size), this technology is able to recognize any specified citizen within the mentioned duration. Moreover, this technology has applications in different fields as many criminals have been captured using this technology within the same rate. This occurs at present. You can imagine if China develops this technology, which is currently being done, this duration will be minimized and the accuracy level will be maximized according to the above stated conclusion.

Not quite there yet in the real world, but Hollywood already is 😉. ZOOM! ENHANCE!
Selfie time: new AR technology in KFC Original+ Beijing will know what you want to eat 🍔🍟

Last year, the biology scientist Craig Venter, one of the greatest scientists in the field of biology, specifically in DNA sequencing, I have ever seen published a research in PNAS journal, illustrating that using DNA, the device can recognize 80% of the faces. If you give the device 10 DNA, for example, it can expect how 8 persons faces will look like. So, with the sample of 1000, it reached an accuracy of 80% in the expectation. So, if this is applied to eg China, you can imagine how high the percentage of accuracy will be in future. Again our face reflects our gene. If you see this issue as not a big deal, I won’t agree with you. As in 1950s we have exerted every effort just to know the structure of the DNA. So, in a nutshell, what ever is hidden in our genes, we can see it on our faces.

Official Apple TouchID Icon. It seems to be happy…

Some readers may say, it is just an identification technology similar to Touch ID and it is not going to save Titanic. I will tell them, you are right, it is not gonna save Titanic, but it is gonna save many health insurance companies. This technology will have a great effect on health insurance companies as from 30-40% of genes’ diseases (genetic disorders manifest craniofacial abnorma) have effect on faces and skulls as Hart and Hart stated in 2009. Health insurance companies can know a lot about your health without making any blood test, just with your facial recognition analysis, which you do not have any will in. This will help insurance underwriter to minimize the risk as much as possible.

To sum up, just using facial recognition technology, the devices can declare our characteristics, orientations, and also behaviors. So are you still interested in iPhone or you will turn to Android

References

Hackdayz #18 – Video

Reading Time: < 1 minute

Our first Hackdayz was a blast! Mid of December 2018 we organized our first Hackdayz. A two day offsite teaming and workshop event for all our employees. The goal: Get something (project) done in 48 hours! We will blog about the details later on… but for now, here are some impressions of us from the Oberwaid in St. Gallen.

My humble expectations on Devoxx Poland 2019

Reading Time: 2 minutes

Five months and devoxx.pl in Krakow has already finished again. That leaves me some time for preparation and anticipation.

Preparation

Key preparations like conference ticket, flight and hotel are done. However, I would be grateful for sightseeing hints for the evenings. Feel free to share them in the comments section.

There are five different tickets available. Generally, you have three alternatives with some optional sugar in form of dinner or gifts.

  • Conference only
  • Deep Dives only
  • Combi (both of them)

I’ve chosen the conference only ticket because I prefer to attend more but shorter slots as the speakers are forced to focus on the key parts. I also liked this format in my last visit at Devox Belgium in 2017.

Anticipation

There is not yet a published schedule but only the list of tracks:

  • Web & HTML5
  • Cloud & Big Data
  • Server Side Java
  • Future <Devoxx>
  • Mobile
  • JVM Languages
  • Methodology
  • Java SE
  • Architecture & Security

And now, those are my expectations for Devoxx Poland

  • New Java language features in 11 and 12.
  • From monolith via microservice to serverless. What’s the next thing?
  • Learn about some new fancy JS frameworks.
  • What’s new in the mobile world and which approach will make us happy: native, hybrid, web views, …?
  • Insights into JVM release roadmap and Oracle subscription models.
  • Enjoy some typical Polish foods and drink.