<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jossy Paul on Medium]]></title>
        <description><![CDATA[Stories by Jossy Paul on Medium]]></description>
        <link>https://medium.com/@jossypaul?source=rss-b13f9b71d3a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CvNP_psh3PmfDvRjRbZlHA.jpeg</url>
            <title>Stories by Jossy Paul on Medium</title>
            <link>https://medium.com/@jossypaul?source=rss-b13f9b71d3a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:55:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jossypaul/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android ViewModel — Should we delegate out presentation logic from ViewModel?]]></title>
            <link>https://jossypaul.medium.com/should-we-delegate-out-viewmodel-functionalities-999dbcb1e8a5?source=rss-b13f9b71d3a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/999dbcb1e8a5</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[viewmodel]]></category>
            <dc:creator><![CDATA[Jossy Paul]]></dc:creator>
            <pubDate>Tue, 24 Aug 2021 13:10:51 GMT</pubDate>
            <atom:updated>2021-09-21T11:06:24.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdV3IhpU9DpA_L5ySnAL8w.jpeg" /></figure><p>In most cases(or at least during the initial phase of development), a ViewModel will normally be developed keeping in mind a single view. As application grows larger, there can be instances where the same presentation logic needs to implemented in different views. We would have a tendency to use the same ViewModel in that view as well. If we need to add another functionality to the new view, we would add that to the old ViewModel. And after several months of development you got yourself a giant ViewModel which holds half the application’s presentation logic.</p><p>From what I can see, we do have three choices to prevent this from happening. The obvious choice is have separate ViewModels for each view. But what about our code reusability? If there is a need for same presentation logic in different views, the code will be duplicated in several ViewModels.</p><p>Other choice is to have really small ViewModels that can be reused in all the views. But then we would need to initialise all these ViewModels in the view making our view bulky. And another issue with this is the case where we are running two api calls in parallel and we want our ProgressBar to be shown as long as either one of them is still loading. These scenarios will be difficult to handle, if we have these two api calls running in separate ViewModels. There is a chance that some of the presentation logic will leak out to the view.</p><p>And what about inheritance? Okay, let’s see whether inheritance can help us out here. We are creating a note taking application. In the first view we have only one functionality: Add notes. Simple, we can create our AddNotesViewModel. Now in the second view we can Add and fetch the notes. Thats also simple, we can inherit from AddNotesViewModel and create FetchAndAddViewModel. But the next requirement is to have a page where user can Fetch and Delete notes. We can inherit from FetchAndAddViewModel. But the issue is that we don’t need Add functionality. There is a very famous analogy about this.</p><blockquote>You asked for a banana, but you got a gorilla holding the banana.</blockquote><p>We can create another ViewModel from scratch. But here we would be duplicating our code. As you can see, inheritance can get more complex with each level.</p><h3><strong>Solution</strong></h3><p>I think <a href="https://kotlinlang.org/docs/delegation.html">kotlin delegation</a> is a great option in these types of scenarios. This allows us to use the principle <a href="https://en.wikipedia.org/wiki/Composition_over_inheritance">“Composition over Inheritance”</a>. The idea here is to create small units of code that is reusable. Whenever we need that functionality, we will just include it to our viewModel using delegates.</p><p>In case what we want in our viewModel is the functionality to add note, we will create a reusable component which has a single responsibility to add notes. Something like this:</p><pre>interface AddNotesDelegate {<br>    var random: LiveData&lt;String&gt;<br>    fun addNote()<br>}<br><br>class AddNotesDelegateImpl @Inject constructor(private val repository: NotesRepository) :<br>    AddNotesDelegate {<br>    private var _random: MutableLiveData&lt;String&gt; = MutableLiveData(&quot;&quot;)<br>    override var random: LiveData&lt;String&gt; = Transformations.map(_random) <strong>{<br>        </strong>&quot;Note added with ID $<strong>it</strong>&quot;<br>    <strong>}<br><br>    </strong>override fun addNote() {<br>        _random.<em>value </em>= repository.addNote().toString()<br>    }<br><br>}</pre><p>Now in our viewmodel we can just use this <strong>AddNotesDelegate.</strong></p><pre>@HiltViewModel<br>class MainViewModel @Inject constructor(private val addNotesDelegateImpl: AddNotesDelegateImpl) : ViewModel(), AddNotesDelegate by addNotesDelegateImpl</pre><p>Now the viewmodel becomes a single line code. It has become really concise. All the logic has been delegated out. If we want Edit Notes functionality, we will delegate out that as well. Now our viewmodel will contain only the functionalities that is required by the view.</p><h3><strong>Conclusion</strong></h3><p>I am not suggesting to delegate out each functionalities inside the viewmodel. But if there are some presentation logic that can be reused in other views, this is a great solution. An important thing to remember while using kotlin delegates in our viewModel is that if we are working with coroutine inside the delegate, we might have to manually pass the viewModelScope to that delegate. If we are using liveData in view layer, then we can use the liveData builder provided by ktx and from there coroutine can be launched.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=999dbcb1e8a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing unit tests for ViewModel]]></title>
            <link>https://jossypaul.medium.com/writing-unit-tests-for-viewmodel-7dd55793d04c?source=rss-b13f9b71d3a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dd55793d04c</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[viewmodel]]></category>
            <dc:creator><![CDATA[Jossy Paul]]></dc:creator>
            <pubDate>Thu, 05 Nov 2020 09:00:46 GMT</pubDate>
            <atom:updated>2020-11-05T10:22:58.504Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzbsS8hopC9P_V4VaHouKg.jpeg" /><figcaption>This image is here just to add some colour and it has nothing to do with Unit testing 😉</figcaption></figure><p>In this age of TDD where we are supposed write tests first and then implement functionality, we are at-least expected to write test cases for our code. Someone new in android development or unit testing might find difficulties to write tests for a ViewModel. In this article we will try to write test cases for some very common scenarios such as:</p><ol><li>Basic class</li><li>Class with dependency(using Mockito)</li><li>ViewModel containing LiveData</li><li>ViewModel which uses coroutines</li><li>ViewModel which uses interface for callbacks</li></ol><p>First let’s create an application which will have a simple login functionality. I just used the login activity template provided in Android Studio (File-&gt;New-&gt; New project-&gt;Login Activity).</p><h3><strong>1. Basic class</strong></h3><p>We will write test case for login method inside LoginDataSource that was generated with the template. I have edited LoginDataSource class to something like this:</p><pre>class LoginDataSource {<br><br>    fun login(username: String, password: String): Result&lt;LoggedInUser&gt; {<br>        return if (username in users) {<br>            val fakeUser = LoggedInUser(java.util.UUID.randomUUID().toString(), username)<br>            Result.Success(fakeUser)<br>        } else {<br>            Result.Error(Exception(&quot;Invalid User&quot;))<br>        }<br>    }<br><br>    private val users = <em>arrayOf</em>(&quot;Joe Paul&quot;, &quot;Jane Doe&quot;, &quot;Peter Parker&quot;)<br>}</pre><p>First we can create a test class by ⌥ Option + ↵ Return on the class name. Select Junit4 and check the setup/@Before option. This will generate a test class for us.</p><p>Let’s see what we need to test in this method. We need to assert that when we pass valid credentials, it will return success. Otherwise it should return error. eg. login(“Joe Paul”, “123456”) should return success and login(“Jacob Zach”, “123456”) should return error.</p><p>Test class will look something like this:</p><pre>class LoginDataSourceTest {<br>    private lateinit var dataSource: LoginDataSource<br><br>    @Before<br>    fun setUp() {<br>        dataSource = LoginDataSource()<br>    }<br><br>    @Test<br>    fun `login with valid credential should return success`() {<br>        <em>assert</em>(dataSource.login(&quot;Joe Paul&quot;, &quot;123456&quot;) is Result.Success)<br>    }<br><br>    @Test<br>    fun `login with invalid credential should return error`() {<br>        <em>assert</em>(dataSource.login(&quot;Jacob Zach&quot;, &quot;123456&quot;) is Result.Error)<br>    }<br>}</pre><p>This is a basic test and I think it is self explanatory. We are creating the data source in setup method and it will be used in test cases.</p><h3>2. Class with dependency</h3><p>Now imagine that the class we are about to test is having some dependency on some other class and it is being passed through the constructor.</p><pre>class LoginRepository(val dataSource: LoginDataSource) {<br><br>    var user: LoggedInUser? = null<br>        private set<br><br>    val isLoggedIn: Boolean<br>        get() = user != null<br><br>    init {<br>        user = null<br>    }<br><br>    fun login(username: String, password: String): Result&lt;LoggedInUser&gt; {<br>        val result = dataSource.login(username, password)<br><br>        if (result is Result.Success) {<br>            setLoggedInUser(result.data)<br>        }<br><br>        return result<br>    }<br><br>    private fun setLoggedInUser(loggedInUser: LoggedInUser) {<br>        this.user = loggedInUser<br>    }<br>}</pre><p>Here dataSource is passed as a parameter through the constructor. What we can test here is when the method login is called with valid credentials isLoggedIn should return true. But here we are dependent on LoginDataSource for making the login call. Imagine if the dataSource making an actual api call for each test. This will take too much time to run the test suite.</p><p>One option is to create a fake data source class. But for that we will be creating an entire new class which serves no functionality and will be used only for testing. Instead we can use Mockito framework to mock the dataSource. Setup mockito like mentioned in this <a href="https://antonioleiva.com/mockito-2-kotlin/">link</a>. We will be using MockitoJUnitRunner to run the test. Here we will be mocking the data source using the Mock annotation which will create a mock object for the LoginDataSource.</p><pre>@Mock<br>private lateinit var dataSource: LoginDataSource</pre><p>As this will be a mock object we need define its required behaviour. Lets say when the login method in dataSource is called, we need to specify its behaviour.</p><pre>Mockito.`when`(dataSource.login(&quot;Joe Paul&quot;, &quot;123456&quot;)).thenReturn(<br>    Result.Success(<br>        LoggedInUser(&quot;1234567890&quot;, &quot;Joe paul&quot;)<br>    )<br>)</pre><p>If we test the scenario when valid user credentials are provided, it will look something like this.</p><pre>@RunWith(MockitoJUnitRunner::class)<br>class LoginRepositoryTest {<br><br>    @Mock<br>    private lateinit var dataSource: LoginDataSource<br>    private lateinit var repository: LoginRepository<br><br>    @Before<br>    fun setUp() {<br>        repository = LoginRepository(dataSource)<br>    }<br><br>    @Test<br>    fun `login with valid credential should set user`() {<br>        Mockito.`when`(dataSource.login(&quot;Joe Paul&quot;, &quot;123456&quot;)).thenReturn(<br>            Result.Success(<br>                LoggedInUser(&quot;1234567890&quot;, &quot;Joe paul&quot;)<br>            )<br>        )<br>        repository.login(&quot;Joe Paul&quot;, &quot;123456&quot;)<br>        <em>assert</em>(repository.isLoggedIn)<br>    }<br>}</pre><h3>3. ViewModel containing LiveData</h3><p>Now we have reached the main section of this article. Everything we mentioned in the previous sections will be applicable here. Let’s have a look at our ViewModel class first.</p><pre>class LoginViewModel(private val loginRepository: LoginRepository, dispatcher: CoroutineDispatcher) : ViewModel() {<br><br>    private val _loginForm = MutableLiveData&lt;LoginFormState&gt;()<br>    val loginFormState: LiveData&lt;LoginFormState&gt; = _loginForm<br><br>    private val inputCredentials = MutableLiveData&lt;Pair&lt;String, String&gt;&gt;()<br>    fun login(username: String, password: String) {<br>        inputCredentials.<em>value </em>= Pair(username, password)<br>    }<br><br>    val loginResult: LiveData&lt;LoginResult&gt; = Transformations.switchMap(inputCredentials) <strong>{<br>        </strong><em>liveData</em>(dispatcher) <strong>{<br>            </strong>val result = loginRepository.login(<strong>it</strong>.first, <strong>it</strong>.second)<br>            if (result is Result.Success) {<br>                emit(LoginResult(success = LoggedInUserView(displayName = result.data.displayName)))<br>            } else {<br>                emit(LoginResult(error = R.string.<em>login_failed</em>))<br>            }<br>        <strong>}<br>    }<br><br>    </strong>fun loginDataChanged(username: String, password: String) {<br>        if (!isUserNameValid(username)) {<br>            _loginForm.<em>value </em>= LoginFormState(usernameError = R.string.<em>invalid_username</em>)<br>        } else if (!isPasswordValid(password)) {<br>            _loginForm.<em>value </em>= LoginFormState(passwordError = R.string.<em>invalid_password</em>)<br>        } else {<br>            _loginForm.<em>value </em>= LoginFormState(isDataValid = true)<br>        }<br>    }<br><br>     fun isUserNameValid(username: String): Boolean {<br>        return if (username.<em>contains</em>(&#39;@&#39;)) {<br>            PatternsCompat.<em>EMAIL_ADDRESS</em>.matcher(username).matches()<br>        } else {<br>            username.<em>isNotBlank</em>()<br>        }<br>    }<br><br>    private fun isPasswordValid(password: String): Boolean {<br>        return password.length &gt; 5<br>    }<br>}</pre><p>We will write a test case for the function <strong>loginDataChanged</strong>. We need to test that livedata loginFormState will hold the correct value during scenarios such as invalid username, invalid password and valid input. First thing we need to remember while writing test case involving LiveData is to add <a href="https://medium.com/@mutkan/what-is-instanttaskexecutorrule-6b436deb2a99">InstantTaskExecutorRule</a> so that the code will run synchronously. For that we need to add the following library to our build.gradle file.</p><pre>testImplementation &quot;android.arch.core:core-testing:1.1.1&quot;</pre><p>We will try to write test case for the scenario when username is invalid.</p><pre>@RunWith(MockitoJUnitRunner::class)<br>class LoginViewModelTest {<br><br>    @Mock<br>    private lateinit var repository: LoginRepository<br>    private lateinit var viewModel: LoginViewModel<br><br>    @Rule<br>    @JvmField<br>    val instantTaskExecutorRule = InstantTaskExecutorRule()<br><br>    @Before<br>    fun setUp() {<br>        viewModel = LoginViewModel(repository)<br>    }<br><br>    @Test<br>    fun `loginDataChanged with valid username should set loginFormState as error`() {<br>        viewModel.loginDataChanged(&quot;&quot;, &quot;123456&quot;)<br>        <em>assert</em>(viewModel.loginFormState.<em>value</em>?.usernameError != null)<br>    }<br>}</pre><p>Here we are asserting that usernameError is not null when we pass an empty username. You can find a great article about testing livedata written by <a href="https://medium.com/u/e0a4c9469bb5">Jose Alcérreca</a> in this <a href="https://medium.com/androiddevelopers/unit-testing-livedata-and-other-common-observability-problems-bb477262eb04">link</a>. An important thing to remember for testing a livedata which is transformed is to attach an observer to that livedata. As we are not transforming livedata here, we skipped adding an observer.</p><h3>4. ViewModel which uses coroutines</h3><p>We can rewrite the login method in our ViewModel in such a way that we are launching a coroutine from ViewModel and the returned data is converted to a LiveData. This is something we have already done in our previous <a href="https://medium.com/@jossypaul/loading-data-from-contentprovider-using-coroutines-and-livedata-34aa5e79b8ba">article</a>. We will be using <a href="https://developer.android.com/topic/libraries/architecture/coroutines">Livedata-ktx</a> for this. Important thing to remember here is to pass our CoroutineDispatcher through constructor instead of hardcoding it to make it more testable. So our viewmodel looks something like this:</p><pre>class LoginViewModel(private val loginRepository: LoginRepository, dispatcher: CoroutineDispatcher) : ViewModel() {<br><br>    private val _loginForm = MutableLiveData&lt;LoginFormState&gt;()<br>    val loginFormState: LiveData&lt;LoginFormState&gt; = _loginForm<br><br>    private val inputCredentials = MutableLiveData&lt;Pair&lt;String, String&gt;&gt;()<br>    fun login(username: String, password: String) {<br>        inputCredentials.<em>value </em>= Pair(username, password)<br>    }<br><br>    val loginResult: LiveData&lt;LoginResult&gt; = Transformations.switchMap(inputCredentials) <strong>{<br>        </strong><em>liveData</em>(dispatcher) <strong>{<br>            </strong>val result = loginRepository.login(<strong>it</strong>.first, <strong>it</strong>.second)<br>            if (result is Result.Success) {<br>                emit(LoginResult(success = LoggedInUserView(displayName = result.data.displayName)))<br>            } else {<br>                emit(LoginResult(error = R.string.<em>login_failed</em>))<br>            }<br>        <strong>}<br>    }<br><br>    </strong>fun loginDataChanged(username: String, password: String) {<br>        if (!isUserNameValid(username)) {<br>            _loginForm.<em>value </em>= LoginFormState(usernameError = R.string.<em>invalid_username</em>)<br>        } else if (!isPasswordValid(password)) {<br>            _loginForm.<em>value </em>= LoginFormState(passwordError = R.string.<em>invalid_password</em>)<br>        } else {<br>            _loginForm.<em>value </em>= LoginFormState(isDataValid = true)<br>        }<br>    }<br><br>    private fun isUserNameValid(username: String): Boolean {<br>        return if (username.<em>contains</em>(&#39;@&#39;)) {<br>            Patterns.<em>EMAIL_ADDRESS</em>.matcher(username).matches()<br>        } else {<br>            username.<em>isNotBlank</em>()<br>        }<br>    }<br><br>    private fun isPasswordValid(password: String): Boolean {<br>        return password.length &gt; 5<br>    }<br>}</pre><p>We have used a switchMap transformation here so that whenever inputCredentials changes, login method will be triggered. How can we test this method? We already know that as we are using transformation here we need to observe the livedata to test it. For that we will use the getOrAwaitValue method mentioned in the <a href="https://medium.com/androiddevelopers/unit-testing-livedata-and-other-common-observability-problems-bb477262eb04">link</a>. Now we move to the coroutines. Jetbrains provides a library which has TestCoroutineDispatcher which can be used in our tests. More about that can be found in this <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/">link</a>.</p><pre>testImplementation &#39;org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.6&#39;</pre><p>Now we can replace our main dispatcher with TestCoroutineDispatcher. For that we can create a custom rule and apply that rule to all the test classes with coroutines.</p><pre>@ExperimentalCoroutinesApi<br>class MainCoroutineRule(<br>    val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()<br>) : TestWatcher() {<br><br>    override fun starting(description: Description?) {<br>        super.starting(description)<br>        Dispatchers.<em>setMain</em>(testDispatcher)<br>    }<br><br>    override fun finished(description: Description?) {<br>        super.finished(description)<br>        Dispatchers.<em>resetMain</em>()<br>        testDispatcher.cleanupTestCoroutines()<br>    }<br>}</pre><p>Finally our test class for ViewModel will look like this:</p><pre>@ExperimentalCoroutinesApi<br>@RunWith(MockitoJUnitRunner::class)<br>class LoginViewModelTest {<br><br>    @Mock<br>    private lateinit var repository: LoginRepository<br>    private lateinit var viewModel: LoginViewModel<br><br>    @Rule<br>    @JvmField<br>    val instantTaskExecutorRule = InstantTaskExecutorRule()<br><br>    @Rule<br>    @JvmField<br>    val testCoroutineRule = MainCoroutineRule()<br><br>    @Before<br>    fun setUp() {<br>        viewModel = LoginViewModel(repository, testCoroutineRule.testDispatcher)<br>    }<br><br>    @Test<br>    fun `login with valid username should set loginResult as success`() {<br>        testCoroutineRule.testDispatcher.<em>runBlockingTest </em><strong>{<br>            </strong>Mockito.`when`(repository.login(&quot;Joe Paul&quot;, &quot;123456&quot;)).thenReturn(<br>                Result.Success(<br>                    LoggedInUser(&quot;31322&quot;, &quot;Joe Paul&quot;)<br>                )<br>            )<br>            viewModel.login(&quot;Joe Paul&quot;, &quot;123456&quot;)<br>            <em>assert</em>(viewModel.loginResult.<em>getOrAwaitValue</em>().success != null)<br>        <strong>}<br>    </strong>}<br>}</pre><p>We are using testDispatcher inside our testCoroutineRule to run the coroutine block. We will assert that loginResult contains a success value if we pass valid credentials.</p><h3>5. ViewModel which uses interface for callbacks</h3><p>Now imagine that we are working some legacy code which is using interfaces for callbacks from our data source or repository class and we don’t want to make any changes in those classes. In this scenario, we will be passing the callback object to our repository through login method. So we will change login method in ViewModel accordingly.</p><pre>fun login(username: String, password: String) {<br>    loginRepository.login(username, password, object : LoginCallback {<br>        override fun dataFetched(result: Result&lt;LoggedInUser&gt;?) {<br>            if (result is Result.Success) {<br>                _loginResult.<em>value </em>=<br>                    LoginResult(success = LoggedInUserView(displayName = result.data.displayName))<br>            } else {<br>                _loginResult.<em>value </em>= LoginResult(error = R.string.<em>login_failed</em>)<br>            }<br>        }<br>    })<br>}</pre><p>LoginCallback.kt</p><pre>interface LoginCallback {<br>    fun dataFetched(result: Result&lt;LoggedInUser&gt;?)<br>}</pre><p>And login method in repository will be:</p><pre>fun login(username: String, password: String, callback: LoginCallback) {<br>    val result = dataSource.login(username, password)<br>    callback.dataFetched(result)<br>}</pre><p>As we have made a mock object for our repository it won’t be able to trigger the ‘dataFetched’ call while running a test. <a href="https://www.baeldung.com/mockito-callbacks">ArgumentCaptor</a> in Mockito comes to our rescue. It will be able to capture the parameter(LoginCallback) we are passing to the login method and we will be able to manually trigger ‘dataFetched’. Mockito also provides <a href="https://www.javatpoint.com/mockito-argument-matchers">ArgumentMatchers</a> which helps us to verify the arguments provided to login method.</p><pre>@Test<br>fun `login with valid username should set loginResult as success`() {<br>    viewModel.login(&quot;Joe Paul&quot;, &quot;123456&quot;)<br>    val captor = ArgumentCaptor.forClass(LoginCallback::class.<em>java</em>)<br>    Mockito.verify(repository).login(eq(&quot;Joe Paul&quot;), eq(&quot;123456&quot;), captor.capture())<br>    captor.<em>value</em>.dataFetched(Result.Success(LoggedInUser(&quot;1234567&quot;, &quot;Joe Paul&quot;)))<br>    <em>assert</em>(viewModel.loginResult.<em>value</em>?.success != null)<br>}</pre><p>If we run this test we will get an NullPointerException saying “eq(“Joe Paul”) must not be null”. This is a known <a href="http://derekwilson.net/blog/2018/08/23/mokito-kotlin#:~:text=Argument%20matchers,match%20with%20it%20using%20Mockito.&amp;text=This%20is%20because%20it%20can,to%20a%20non%2Dnullable%20parameter.">issue</a> when we use mockito in kotlin. In android architecture sample <a href="https://github.com/android/architecture-samples/blob/todo-mvp-kotlin/todoapp/app/src/test/java/com/example/android/architecture/blueprints/todoapp/MockitoKotlinHelpers.kt">code</a>, they are providing some fixes for this issue by adding the following methods. In this article we will using that. Otherwise you can always use the <a href="https://github.com/nhaarman/mockito-kotlin">mockito-kotlin</a> library.</p><pre>fun &lt;T&gt; eq(obj: T): T = Mockito.eq&lt;T&gt;(obj)<br>fun &lt;T&gt; any(): T = Mockito.any&lt;T&gt;()<br>fun &lt;T&gt; capture(argumentCaptor: ArgumentCaptor&lt;T&gt;): T = argumentCaptor.capture()<br>inline fun &lt;reified T : Any&gt; argumentCaptor(): ArgumentCaptor&lt;T&gt; =<br>    ArgumentCaptor.forClass(T::class.<em>java</em>)</pre><p>Until mockito comes up with their own solution I think we can use either of them. So our final test class which uses the new methods will look like this:</p><pre>@RunWith(MockitoJUnitRunner::class)<br>class LoginViewModelTest {<br><br>    @Mock<br>    private lateinit var repository: LoginRepository<br>    private lateinit var viewModel: LoginViewModel<br><br>    @Rule<br>    @JvmField<br>    val instantTaskExecutorRule = InstantTaskExecutorRule()<br><br>    @Before<br>    fun setUp() {<br>        viewModel = LoginViewModel(repository)<br>    }<br><br>    @Test<br>    fun `login with valid username should set loginResult as success`() {<br>        viewModel.login(&quot;Joe Paul&quot;, &quot;123456&quot;)<br>        val captor = <em>argumentCaptor</em>&lt;LoginCallback&gt;()<br>        Mockito.verify(repository).login(<em>eq</em>(&quot;Joe Paul&quot;), <em>eq</em>(&quot;123456&quot;), <em>capture</em>(captor))<br>        captor.<em>value</em>.dataFetched(Result.Success(LoggedInUser(&quot;1234567&quot;, &quot;Joe Paul&quot;)))<br>        <em>assert</em>(viewModel.loginResult.<em>value</em>?.success != null)<br>    }<br>}</pre><h3>Conclusion</h3><p>In this article we tried to cover some common scenarios in a viewmodel although we have excluded rxjava and coroutine flow. Please let me know in the comments if you have any suggestions, improvements or queries.</p><h3>References</h3><ul><li><a href="https://medium.com/@jossypaul/loading-data-from-contentprovider-using-coroutines-and-livedata-34aa5e79b8ba">Loading data from ContentProvider using Coroutines and LiveData</a></li><li><a href="https://medium.com/androiddevelopers/unit-testing-livedata-and-other-common-observability-problems-bb477262eb04">Unit-testing LiveData and other common observability problems</a></li><li><a href="https://antonioleiva.com/mockito-2-kotlin/">How to mock final classes on Kotlin using Mockito 2</a></li><li><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/">kotlinx-coroutines-test</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dd55793d04c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MotionLayout - Simplest way to create beautiful Animations in Android]]></title>
            <link>https://jossypaul.medium.com/motionlayout-simplest-way-to-create-beautiful-animations-in-android-9935db529e75?source=rss-b13f9b71d3a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9935db529e75</guid>
            <category><![CDATA[android-animations]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[collapsing-toolbar]]></category>
            <category><![CDATA[motionlayout]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jossy Paul]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 12:27:36 GMT</pubDate>
            <atom:updated>2020-08-30T06:14:20.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVz53ONjrXjHyRD6ZXP2hQ.jpeg" /><figcaption>3 year before Covid-19 (3 BC)</figcaption></figure><blockquote>MotionLayout is a layout type that helps you manage motion and widget animation in your app. MotionLayout is a subclass of ConstraintLayout and builds upon its rich layout capabilities.- Says Developer Site</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oL1GAmTnNXk3y19I8qyenw.gif" /></figure><p>A week ago I wasn’t even aware that there is a MotionLayout in android. Now that I have started learning it, I can’t believe how easy it is to implement these kind of animations without writing a single line of code in your activity. Before anyone gets too excited about animating the curved bottom portion of image, I have to confess that I am doing this by putting curved image on top of the main image. Not sure whether this is the best way to implement it. But it could be the simplest way.</p><p>So that out of the way, let’s analyse the animation that we are about to implement using MotionLayout. Let’s start from the top:</p><ol><li>Image at the top transforming to a toolbar. ie. we have to decrease its height and gradually change its image to the background of toolbar.</li><li>In oder to achieve the effect of curved ImageView we will draw a curve on top of the ImageView using a vector. And we will decrease its size to zero as it moves up so that will get a morphing effect.</li><li>Just before the animation ends, we have to gradually increase the elevation of toolbar aka our ‘ImageView’. So that user will get a feeling that the text is scrolled under the toolbar.</li><li>Heading(Manali) size should be decreased as animation moves up.</li><li>A trigger that initiates this animation. In our case it will be the swipe gesture on the scrollview at the bottom.</li></ol><p>Now let’s start implementing this animation. To implement MotionLayout we need two xml file. One is the actual layout. The other one will be a MotionScene which will contain the starting and ending constraints of views in an animation.</p><p>We bind the MotionScene to our layout by setting it as the layoutDescription in our <strong>activity_main.xml</strong>.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.motion.widget.MotionLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/parent&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:background=&quot;@color/colorPrimary&quot;<br>    app:layoutDescription=&quot;@xml/activity_main_scene&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;androidx.constraintlayout.utils.widget.ImageFilterView<br>        android:id=&quot;@+id/iv_top&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:adjustViewBounds=&quot;true&quot;<br>        android:background=&quot;@color/colorPrimary&quot;<br>        android:contentDescription=&quot;@string/top&quot;<br>        android:scaleType=&quot;centerCrop&quot;<br>        android:src=&quot;@drawable/mountain&quot;<br>        app:altSrc=&quot;@drawable/test_vector&quot;<br>        app:layout_constraintBottom_toTopOf=&quot;@id/scroll_view&quot;<br>        app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>        app:layout_constraintRight_toRightOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;androidx.core.widget.NestedScrollView<br>        android:id=&quot;@+id/scroll_view&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@id/iv_top&quot;&gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_margin=&quot;8dp&quot;<br>            android:fontFamily=&quot;sans-serif-light&quot;<br>            android:text=&quot;@string/stub&quot;<br>            android:textSize=&quot;24sp&quot; /&gt;<br><br>    &lt;/androidx.core.widget.NestedScrollView&gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/iv_curve&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:adjustViewBounds=&quot;true&quot;<br>        android:importantForAccessibility=&quot;no&quot;<br>        android:scaleType=&quot;fitXY&quot;<br>        android:src=&quot;@drawable/curve&quot;<br>        app:layout_constraintBottom_toTopOf=&quot;@id/scroll_view&quot;<br>        app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>        app:layout_constraintRight_toRightOf=&quot;parent&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/tv_heading&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:elevation=&quot;12dp&quot;<br>        android:fontFamily=&quot;sans-serif-condensed-medium&quot;<br>        android:text=&quot;@string/place&quot;<br>        android:textColor=&quot;@color/white&quot;<br>        android:textSize=&quot;50sp&quot;<br>        app:layout_constraintBottom_toTopOf=&quot;@id/scroll_view&quot;<br>        app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>        app:layout_constraintRight_toRightOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br>&lt;/androidx.constraintlayout.motion.widget.MotionLayout&gt;</pre><p>As you can see here, we have not set the constraints here. That will be set inside a ConstraintSet in the MotionScene.</p><p>We are using ImageFilterView which allows us to switch between two images in an animation. The image specified in the altSrc will be the toolbar background. We will use this to transform the mountain image to toolbar.</p><p>Now in order to make the imagview with curved bottom we will create a vectordrawable <strong>curve.xml </strong>that will be set on to <strong>iv_curve</strong>.</p><pre>&lt;vector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:width=&quot;100dp&quot;<br>    android:height=&quot;8dp&quot;<br>    android:viewportWidth=&quot;100.0&quot;<br>    android:viewportHeight=&quot;8.0&quot;&gt;<br>    &lt;path<br>        android:fillColor=&quot;@color/colorPrimary&quot;<br>        android:pathData=&quot;L0,8 100,8 100,0 C100,0 50,17 0,0&quot; /&gt;<br>&lt;/vector&gt;</pre><p>This will be our MotionScene which will contain 2 ConstraintSets <strong>activity_main_scene.xml</strong>. One will be the starting ConstraintSet and other will be the ending ConstraintSet.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;MotionScene&gt;<br>    &lt;ConstraintSet android:id=&quot;@+id/start&quot;&gt;<br>        &lt;Constraint<br>            android:id=&quot;@id/iv_curve&quot;.. /&gt;<br>        &lt;Constraint<br>            android:id=&quot;@id/tv_heading&quot;.. /&gt;<br>    &lt;/ConstraintSet&gt;<br><br>    &lt;ConstraintSet android:id=&quot;@+id/end&quot;&gt;<br>        &lt;Constraint<br>            android:id=&quot;@id/iv_curve&quot;.. /&gt;<br>        &lt;Constraint<br>            android:id=&quot;@id/tv_heading&quot;.. /&gt;<br>    &lt;/ConstraintSet&gt;<br>&lt;/MotionScene&gt;</pre><p>We have to fill up it with the respective constraints for each views and our final <strong>activity_main_scene.xml</strong> will be like this.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;MotionScene xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;<br><br>    &lt;ConstraintSet android:id=&quot;@+id/start&quot;&gt;<br>        &lt;Constraint android:id=&quot;@id/iv_top&quot;&gt;<br>            &lt;CustomAttribute<br>                app:attributeName=&quot;crossfade&quot;<br>                app:customFloatValue=&quot;0&quot; /&gt;<br>        &lt;/Constraint&gt;<br>    &lt;/ConstraintSet&gt;<br><br>    &lt;ConstraintSet<br>        android:id=&quot;@+id/end&quot;<br>        app:deriveConstraintsFrom=&quot;@id/start&quot;&gt;<br>        &lt;Constraint android:id=&quot;@id/iv_top&quot;&gt;<br>            &lt;Transform android:translationZ=&quot;10dp&quot;/&gt;<br>            &lt;Layout<br>                android:layout_height=&quot;60dp&quot;<br>                app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>                app:layout_constraintRight_toRightOf=&quot;parent&quot;<br>                app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br>            &lt;CustomAttribute<br>                app:attributeName=&quot;crossfade&quot;<br>                app:customFloatValue=&quot;1&quot; /&gt;<br>        &lt;/Constraint&gt;<br>        &lt;Constraint<br>            android:id=&quot;@id/iv_curve&quot;<br>            android:layout_height=&quot;0dp&quot;<br>            app:layout_constraintBottom_toTopOf=&quot;@id/scroll_view&quot;<br>            app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>            app:layout_constraintRight_toRightOf=&quot;parent&quot; /&gt;<br>        &lt;Constraint android:id=&quot;@id/tv_heading&quot;&gt;<br>            &lt;Transform<br>                android:scaleX=&quot;.5&quot;<br>                android:scaleY=&quot;.5&quot; /&gt;<br>        &lt;/Constraint&gt;<br><br>    &lt;/ConstraintSet&gt;<br><br>    &lt;Transition<br>        app:constraintSetEnd=&quot;@id/end&quot;<br>        app:constraintSetStart=&quot;@+id/start&quot;&gt;<br>        &lt;KeyFrameSet&gt;<br>            &lt;KeyAttribute<br>                android:translationZ=&quot;0dp&quot;<br>                app:framePosition=&quot;99&quot;<br>                app:motionTarget=&quot;@id/iv_top&quot; /&gt;<br>        &lt;/KeyFrameSet&gt;<br>        &lt;OnSwipe app:touchAnchorId=&quot;@+id/scroll_view&quot; /&gt;<br>    &lt;/Transition&gt;<br>&lt;/MotionScene&gt;</pre><p>In the starting ConstraintSet we will specify height of iv_curve as wrap_content and in the ending ConstraintSet we will specify it as 0dp. This will create morphing effect to the imageview’s bottom.</p><p>Inside Constraint of iv_top we use CustomAttribute tag to fade between two images. Initial image will be the mountain and it will be faded to toolbar background colour as animation progresses. We will use the crossfade here.</p><p>In the Transition tag we have to specify the gesture with which this animation occurs. So we will use the <strong>OnSwipe</strong> and specify the touchAnchorId which will be our scroll view.</p><p>Now we want the elevation change of toolbar to be starting only towards the end of animation. Let’s imagine if the overall length of this animation is 100 frames, then we want the elevation to be increasing at the 99th frame. For that we’ll use KeyFrameSet. Here we can specify any attribute at a particular framePosition. As we need the elevation at that point to be zero, we will specify that using translationZ. And in ConstraintSet for the end of animation we will specify translationZ as 10dp.</p><p>That’s it. We have implemented some nice animations in no time.</p><h3>References</h3><p><a href="https://blog.mindorks.com/getting-started-with-motion-layout-android-tutorials">https://blog.mindorks.com/getting-started-with-motion-layout-android-tutorials</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9935db529e75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loading data from ContentProvider using Coroutines and LiveData]]></title>
            <link>https://jossypaul.medium.com/loading-data-from-contentprovider-using-coroutines-and-livedata-34aa5e79b8ba?source=rss-b13f9b71d3a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/34aa5e79b8ba</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[contentprovider]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[livedata]]></category>
            <dc:creator><![CDATA[Jossy Paul]]></dc:creator>
            <pubDate>Tue, 26 May 2020 06:45:44 GMT</pubDate>
            <atom:updated>2020-11-24T10:12:04.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4vxjVnr9Hu8uq4-zXDtTEg.png" /><figcaption>MVVM architecture of content provider sample app we are about to build</figcaption></figure><p>Most of the ContentProvider tutorials shows us loading data using <a href="https://developer.android.com/reference/androidx/loader/content/CursorLoader">CursorLoader</a>. As android development is moving away from Loaders and asyncTasks, I think we should consider implementing these things using alternatives like coroutine. Through this story we’ll be trying to load data from content provider using coroutine and show it on a list.</p><p>We will build a sample app which load contacts from content provider trying to follow the recommended <a href="https://developer.android.com/jetpack/docs/guide#overview">app architecture</a>. You can replace it with any content provider you want. Before starting to code let’s add the dependencies for Coroutines, livedata-ktx and gilde.</p><pre>implementation &#39;androidx.lifecycle:lifecycle-livedata-ktx:2.2.0&#39;<br>implementation &#39;androidx.recyclerview:recyclerview:1.1.0&#39;<br>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.6&quot;<br>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3&quot;<br>implementation &#39;com.github.bumptech.glide:glide:4.11.0&#39;<br>annotationProcessor &#39;com.github.bumptech.glide:compiler:4.10.0&#39;</pre><p>Generally we would have been using a cursor loader for loading the contacts from the content provider. But here we will be using Coroutines which are basically a light weighted thread that is available in kotlin. LiveData ktx is a kotlin extension for livedata which helps us to convert data loaded in the coroutine block into a LiveData. You can read more about it <a href="https://developer.android.com/kotlin/ktx?gclid=Cj0KCQjwirz3BRD_ARIsAImf7LNYtbqYdIEon1lLl0fz-VFQoaQM6CK2kTdi7668PZj1-_BGTJRCy-gaAuVkEALw_wcB&amp;gclsrc=aw.ds#livedata">here</a>. We will be using Glide library for showing the contact images on an imageview.</p><p>Now let’s start coding. First we have to setup our model class and data source.</p><pre>data class MyContact(val name: String, val image: String)</pre><p>Our data source will be like this:</p><pre>class MyContactsDataSource(private val contentResolver: ContentResolver) {<br><br>    fun fetchContacts(): List&lt;MyContact&gt; {<br>        val result: MutableList&lt;MyContact&gt; = <em>mutableListOf</em>()<br><br>        val cursor = contentResolver.query(<br>            ContactsContract.Data.<em>CONTENT_URI</em>,<br>            <em>arrayOf</em>(<br>                ContactsContract.CommonDataKinds.Phone.<em>DISPLAY_NAME</em>,<br>                ContactsContract.CommonDataKinds.Phone.<em>CONTACT_ID<br>            </em>),<br>            null,<br>            null,<br>            ContactsContract.CommonDataKinds.Phone.<em>DISPLAY_NAME<br>        </em>)<br>        cursor?.<em>let </em><strong>{<br>            </strong>cursor.moveToFirst()<br>            while (!cursor.<em>isAfterLast</em>) {<br>                result.add(<br>                    MyContact(<br>                        cursor.getString(0),<br>                        cursor.getString(1).<em>toContactImageUri</em>()<br>                    )<br>                ) //add the item<br>                cursor.moveToNext()<br>            }<br>            cursor.close()<br>        <strong>}<br><br>        </strong>return result.<em>toList</em>()<br>    }<br><br>}<br><br>fun String.toContactImageUri() = Uri.withAppendedPath(<br>    ContentUris.withAppendedId(ContactsContract.Contacts.<em>CONTENT_URI</em>, this.<em>toLong</em>()),<br>    ContactsContract.Contacts.Photo.<em>CONTENT_DIRECTORY<br></em>).toString()</pre><p>Nothing fancy is happening here in the data source. We are loading cursor which contains DISPLAY_NAME and CONTACT_ID<em> </em>from the CONTENT_URI<em> </em>for contacts to a list of MyContact object. The extension method toContactImageUri will convert CONTACT_ID to the path of contact image. As you can see here we are using the uri for contacts, you can replace it with any content provider uri which you will be loading.</p><p>And now the repository will be like this:</p><pre>class MyContactsRepository(private val source: MyContactsDataSource, private val myDispatcher: CoroutineDispatcher) {<br><br>    suspend fun fetchContacts(): List&lt;MyContact&gt; {<br>        return <em>withContext</em>(myDispatcher) <strong>{<br>            </strong>source.fetchContacts()<br>        <strong>}<br>    </strong>}<br>}</pre><p>Here withContext lets you control what thread source.fetchContacts() executes on. <strong>myDispatcher</strong> will be the CoroutineDispatcher on which <strong>fetchContacts() </strong>will run. As we are doing an IO operation we’ll be using <strong>Dispatchers.IO. </strong>This will keep us off the main thread while doing DB operations. Instead of hardcoding our dispatcher in the repository, we’ll be passing it through the constructor to make testing easier. I have covered more about testing in <a href="https://jossypaul.medium.com/writing-unit-tests-for-viewmodel-7dd55793d04c">this</a> article.</p><p>From <strong>MainViewModel</strong>, we call our repository for fetching the data.</p><pre>class MainViewModel(<br>    context: Application,<br>    private val myContactsRepository: MyContactsRepository<br>) : AndroidViewModel(context) {<br><br>    var myContacts: LiveData&lt;List&lt;MyContact&gt;&gt; = <em>liveData </em><strong>{<br>        </strong>emit(myContactsRepository.fetchContacts())<br>    <strong>}<br><br></strong>}</pre><p>Here we are using the <strong><em>liveData</em></strong><em> </em>builder which returns a LiveData. We will be able to run a coroutine block inside this and can emit the results to a LiveData. The coroutine block will start running after an observer is attached to the LiveData. More details on liveData builder can be found in this <a href="https://developer.android.com/topic/libraries/architecture/coroutines#livedata">link</a>.</p><p>Let’s create our viewmodel factory class for creating our viewmodels.</p><pre>class MyViewModelFactory(private val application: Application) :<br>    AndroidViewModelFactory(application) {<br>    override fun &lt;T : ViewModel?&gt; create(modelClass: Class&lt;T&gt;): T {<br>        return if (modelClass.isAssignableFrom(MainViewModel::class.<em>java</em>)) {<br>            val source =<br>                MyContactsDataSource(application.<em>contentResolver</em>)<br>            MainViewModel(application, MyContactsRepository(source, Dispatchers.IO)) as T<br>        } else<br>            throw IllegalArgumentException(&quot;Unknown ViewModel class&quot;)<br>    }<br>}</pre><p>That’s it, we have created our viewmodel. We can fetch the content provider data from our views. Let’s say we are fetching the data from an activity and populating it onto a recyclerview. First we have to create an adapter for our recyclerview for this.</p><pre>class MyContactsAdapter : ListAdapter&lt;MyContact, ViewHolder&gt;(DiffCallback()) {<br>    // Inflates the item views<br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {<br>        return ViewHolder(<br>            LayoutInflater.from(parent.<em>context</em>).inflate(<br>                R.layout.<em>contact_list_item</em>,<br>                parent,<br>                false<br>            )<br>        )<br>    }<br><br>    override fun onBindViewHolder(holder: ViewHolder, position: Int) {<br>        holder.bind(getItem(position))<br>    }<br>}<br><br>class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {<br>    private val tvImage: ImageView = itemView.ivCharacter<br>    private val tvName: TextView = itemView.tvName<br>    fun bind(item: MyContact) {<br>        tvName.<em>text </em>= item.name<br>        Glide.with(tvImage)<br>            .load(item.image)<br>            .into(tvImage)<br>    }<br>}<br><br>class DiffCallback : DiffUtil.ItemCallback&lt;MyContact&gt;() {<br>    override fun areItemsTheSame(oldItem: MyContact, newItem: MyContact): Boolean {<br>        return oldItem.name == newItem.name<br>    }<br><br>    override fun areContentsTheSame(oldItem: MyContact, newItem: MyContact): Boolean {<br>        return oldItem == newItem<br>    }<br>}</pre><p>Our <em>contact_list_item </em>will be:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:id=&quot;@+id/itemParent&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;&gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/ivCharacter&quot;<br>        android:layout_width=&quot;100dp&quot;<br>        android:layout_height=&quot;100dp&quot;<br>        android:contentDescription=&quot;@string/app_name&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/tvName&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toEndOf=&quot;@id/ivCharacter&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;/&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>And our activity_main.xml:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.recyclerview.widget.RecyclerView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/parentView&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:background=&quot;#777&quot;<br>    tools:context=&quot;.main.MainActivity&quot;&gt;<br>&lt;/androidx.recyclerview.widget.RecyclerView&gt;</pre><p>In our activity we will be observing the data inside our viewmodel.</p><pre>class MainActivity : AppCompatActivity() {<br><br>    private val adapter = MyContactsAdapter()<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        val myViewModelFactory =<br>            MyViewModelFactory(<em>application</em>)<br>        val viewModel = ViewModelProvider(this, myViewModelFactory).get(MainViewModel::class.<em>java</em>)<br>        setContentView(R.layout.<em>activity_main</em>)<br>        parentView.<em>layoutManager </em>= LinearLayoutManager(this)<br>        parentView.<em>adapter </em>= adapter<br>        viewModel.myContacts.observe(this, <em>Observer </em><strong>{<br>            </strong>adapter.submitList(<strong>it</strong>)<br>        <strong>}</strong>)<br>    }<br>}</pre><h3>Conclusion</h3><p>Using coroutine and LiveData we can keep our activities lean and we don’t have bloat it with all the loader callbacks.</p><p>Note: Please add the necessary runtime permissions if you are using the contacts.</p><h3>References</h3><ul><li><a href="https://medium.com/@velasco622/easy-coroutines-in-android-livedata-builder-withcontext-and-dispatchers-f4b3fc5a33fc">Easy Coroutines in Android: liveData() builder, withContext(), and Dispatchers</a></li><li><a href="https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb">Coroutines on Android (part I): Getting the background</a></li><li><a href="https://medium.com/@hackathon.blog.42/listadapter-renewed-9b5b496198e2">ListAdapter renewed</a></li><li><a href="https://medium.com/@saranyaan2710/content-provider-in-android-basics-d219cf42574d">Content Provider in Android — Basics</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34aa5e79b8ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>