Android MVVM architectural design pattern with RxJava in Kotlin

Sharing is caring!

To build an awesome android application, Architectural design pattern plays an important role. It makes our code modular and communication with different components becomes easy. By using Architectural design we can build an application which can be testable and maintainable easy in the future or whenever we want to add a new feature or remove a feature, it will not cause any complication.

There are many design pattern available to build awesome apps like MVP (Model View Presenter), MVVM (Model View View Model) and Android  Architectural design Component recently given by Google. Picking any design pattern is the little bit difficult to decide. Its all about depend on Android Developers that which design pattern they like most. Every design pattern works nicely with all component.

MVVM Android Architectural design:

In this tutorial, we will discuss the MVVM Android Architectural design to use to build the awesome android application.

Model: Model represents the classes that used for creating the business model of an application. It means how the data can manipulate.

View: View represents the user interface means Button or TextView. View displays the data from the model.The view which binds with Observable variables and action triggered for ViewModel.

ViewModel: ViewModel is a middle layer for interaction between the View and model. Its responsibility is preparing the Observable data which is needed to view and also hooks for model event triggered from view.
This pattern is using the data binding concept which means that multiple views contain single ViewModel. ViewModel should have all the information which is required for the view.  In this case, ViewModel that can be reused for multiple views. For Single ViewModel interaction for a module, our debug and unit testing becomes easy. A developer can find the issue easily and it makes easy to add any new feature to existing code. Overall it makes our life pretty easy & simple.

Your data update or change should be aware of lifecycle otherwise it will memory leak. If you are using the RxJava Observable sequence then make sure that it uses the correct way because RxJava is not aware of Lifecycle. Always try to use LiveData and Databinding ObservaleField for the better result because they are aware of lifecycle event and avoid the memory leaks. Here You can learn  Why is necessary to take care of android memory leaks?

To understand the reactive Rx I would be recommended to check these posts of understanding of Java 8 stream and Rx Observables, and basic understanding and practice features and functions of RxJava, and understanding practice RxJava with RxBinding in Android.

Let’s take an example of MVVM with Databinding ObservaleField and RxJava to send the tweet to our timeLines.

class TimelineFragmentViewModel{

     fun sendTweet(tweetText: String): Observable<Result<Tweet>> {
        return Observable.create { subscriber ->
            val callback = object : Callback<Tweet>() {
                override fun success(result: Result<Tweet>) {
                    Log.i(TAG, "Tweet tweeted")
                    subscriber.onNext(result)
                }

                override fun failure(e: TwitterException) {
                    Log.e(TAG, e.message, e)
                    subscriber.onError(e)
                }
            }

            TwitterCore.getInstance().apiClient.statusesService.update(tweetText, null, null, null, null, null, null, null, null).enqueue(callback)
        }
    }
}

I have created the TimeLineFragmentViewModel is a ViewModel to handle all the business logic will be here. I used the Twitter API call to send a tweet to Twitter and get the result of the tweet from Twitter API client. Here callback result is subscribed to the publisher by using the RxJava.  Now, let’s check how is this ViewModel is communicating with View?

class TimelineFragment : Fragment() {

    private var binding: FragmentTimelineBinding? = null
    private var timelineFragmentVM: TimelineFragmentViewModel? = null

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout and attach the ViewModel for this fragment
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_timeline, container, false)
        val view: View = binding!!.root
        timelineFragmentVM = TimelineFragmentViewModel(this)
        binding!!.vm = timelineFragmentVM

        //............................
        return view
    }

   
    private fun showNewTweetDialog() {
     //.............................................
        val builder = AlertDialog.Builder(activity)
        builder.setMessage(R.string.label_what_is_happening)
        builder.setPositiveButton(R.string.action_tweet) { dialog, which ->
            timelineFragmentVM!!.sendTweet(tweetText.text.toString()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                            { x ->
                                if (timelineFragmentVM != null) {
                                    showMessage(getString(R.string.alert_tweet_successful))
                                    mutableList.add(0,x.data)
                                   // onTimelineRefresh(mutableList) //update timeline
                                }
                            },
                            { e ->
                                if (timelineFragmentVM != null) {
                                    showMessage(getString(R.string.alert_tweet_failed))
                                }
                            })
        }

        val alert = builder.create()
        alert.setView(tweetText, 64, 0, 64, 0)
        alert.show()

        tweetText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                alert.getButton(DialogInterface.BUTTON_POSITIVE).callOnClick()
                true
            }
            false
        }
    }
}

We can use DataLayer in XML to bind the model directly.

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fragment_main">

    <data>
        <variable name="vm" type="com.sunil.twitterkotlinmvvm.viewmodel.TimelineFragmentViewModel" />
    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        tools:context="com.sunil.twitterkotlinmvvm.ui.TimelineFragment">

        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:visibility="@{vm.isLoading()}" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/timeline_recview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

    </FrameLayout>

</layout>

Here Data change or update will observe by Observable to update the view by using RxAndroid Scheduler MainThread. It can be subscribed with success or failure the causing of exception.

Now suppose in future if any new requirement comes, for example, we will support offline then here we need to change a few things in ViewModel, others remain the same especially View part. It means it will not create so compilation to update or add any new feature because our code structure is modular that makes the Unit Test easy. Here you can learn the basics of Kotlin.

If You are wondering the MVP design pattern with RxJava then I would be recommended to check this post to get help MVP Acrcutureal design pattern with RxJava. Here you can get the full source code from Github of MVVM with Kotlin.

You should always take priority while developing an android application in term of performance, write less code by using the best data structure and application should be used less memory. Here you can learn about the Android application performance and stability is really mattered?

Summary:

Now we have a good understanding of Android MVVM Architectural design pattern with Reactive Native.

If you are wondering to learn Android then Please Learn from Android category and wondering to lean Kotlin then Kotlin Category will help you. If you want to learn all the python article, then learn from the python category.

Please do subscribe email to get every newsletter on this blog and if you feel that this post will help you to better understand then do not forget to subscribe, share and comment below.

Happy coding 🙂

0 0 votes
Article Rating
Android MVVM architectural design pattern with RxJava in Kotlin
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Scroll to top
0
Would love your thoughts, please comment.x
()
x