<?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 Teng Tonghann on Medium]]></title>
        <description><![CDATA[Stories by Teng Tonghann on Medium]]></description>
        <link>https://medium.com/@tengtonghann?source=rss-25ad59c64d61------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VJjW_1YGDwiCDNEyx4_trQ.jpeg</url>
            <title>Stories by Teng Tonghann on Medium</title>
            <link>https://medium.com/@tengtonghann?source=rss-25ad59c64d61------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:34:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tengtonghann/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[Basic Android MVVM with Kotlin Coroutines and Retrofits]]></title>
            <link>https://tengtonghann.medium.com/basic-android-mvvm-with-kotlin-coroutines-and-retrofits-6b0581951fcc?source=rss-25ad59c64d61------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b0581951fcc</guid>
            <category><![CDATA[retrofit2]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Teng Tonghann]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 04:13:10 GMT</pubDate>
            <atom:updated>2020-12-21T04:13:10.478Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Basic Android MVVM with Kotlin Coroutines and Retrofit</strong></h3><p>When developing an Android application it is important to plan the architecture of the project. This will allow us to create good quality code and easy to maintain applications.</p><p>This article will focus on how to use Retrofit with Kotlin Coroutines to call asynchronous REST Api with MVVM architecture.</p><p><strong>The project<br></strong>We will be using the <a href="https://dog.ceo/dog-api/"><strong><em>Dog CEO API</em></strong></a> 🐶 to get random puppy images, and we will be using an image loading library called <a href="https://github.com/bumptech/glide"><strong><em>Glide</em></strong></a> to display the image. Simple!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*sZzlaxmnnLyhJCvJfROhnw.jpeg" /></figure><p>Set up a new project with Kotlin and other dependencies required:</p><pre>def lifecycle_version = &quot;2.2.0&quot;<br><br>// ViewModel<br>implementation &quot;androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version&quot;<br><br>// LiveData<br>implementation &quot;androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version&quot;<br><br>// Retrofit<br>implementation &quot;com.squareup.retrofit2:retrofit:2.9.0&quot;<br>implementation &#39;com.squareup.retrofit2:converter-gson:2.8.1&#39;<br><br>// Coroutines<br>implementation &#39;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7&#39;<br>implementation &#39;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7&#39;</pre><pre>// Loading images - Glide<br>implementation &#39;com.github.bumptech.glide:glide:4.11.0&#39;</pre><ul><li><a href="https://developer.android.com/jetpack/androidx/releases/lifecycle">ViewModel and LiveData</a>: Lifecycle-aware components perform actions in response to a change in the lifecycle status of another component, such as activities and fragments. These components help you produce better-organized, and often lighter-weight code, that is easier to maintain.</li><li><a href="https://square.github.io/retrofit/">Retrofit</a>: A type-safe HTTP client for Android.</li><li><a href="https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html">Coroutines</a>: for asynchronous programming</li><li><a href="https://github.com/bumptech/glide">Glide</a>: supports fetching, decoding, and displaying video stills, images, and animated GIFs.</li></ul><p><strong>Setting up a Model class <br></strong>We will create a model class called ApiResponse which will be a representation of this response JSON.</p><pre>data class ApiResponse (<br>    var message: String,<br>    var status: String<br>)</pre><p><strong>Setting up the Network Layer<br></strong>Since we are using Retrofit for Network calls, let’s create a class that provides us the instance of the Retrofit Service class.</p><ul><li><strong>Creating the Retrofit instance<br></strong>To send out network requests to an API, we need to use the ServiceBuilder class.</li></ul><pre>object ServiceBuilder {<br><br>    private const val API_URL = &quot;https://dog.ceo/api/breeds/&quot;<br><br>    private fun provideRetrofit(): Retrofit {<br>        return Retrofit.Builder()<br>            .baseUrl(API_URL)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>    }<br><br>    val apiService: ApiService by <em>lazy </em><strong>{<br>        </strong>provideRetrofit().create(ApiService::class.<em>java</em>)<br>    <strong>}<br><br></strong>}</pre><ul><li><strong>Define the Endpoints<br></strong>With Retrofit, endpoints are defined inside of an interface using special Retrofit annotations to endcode details about the parameter and request method. The ApiService interface will look as follows.</li></ul><pre>interface ApiService {<br><br>    @GET(&quot;image/random&quot;)<br>    suspend fun getRandomDog(): Response&lt;ApiResponse&gt;<br>}</pre><p>The suspend functions can only be called from Coroutines. Suspend functions are a core element of Coroutines. They help the Coroutines to suspend (paused) or resumed during execution.</p><ul><li><strong>Android Permission<br></strong>let’s add permission in the AndroidManifest file.</li></ul><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</pre><p><strong>Setting up the ViewModel<br></strong>Let’s create our ViewModel class called MainViewModel</p><pre>class MainViewModel : ViewModel(), CoroutineScope by <em>MainScope</em>() {<br><br>    companion object {<br>        const val LOG = &quot;GetDogLog&quot;<br>    }<br><br>    private val _message = MutableLiveData&lt;String&gt;()<br>    val message: LiveData&lt;String&gt;<br>        get() = _message<br><br>    fun getRandomDog() {<br>        <em>launch</em>(Dispatchers.Main) <strong>{<br>            </strong>try {<br>                val response = ServiceBuilder.apiService.getRandomDog()<br>                if (response.<em>isSuccessful </em>&amp;&amp; response.body() != null) {<br>                    response.body()?.message?.<em>let </em><strong>{<br>                        </strong>_message.<em>value </em>= <strong>it<br>                        </strong>Log.d(LOG, <strong>it</strong>)<br>                    <strong>}<br>                </strong>} else {<br>                    Log.d(LOG, &quot;Server error&quot;)<br>                }<br>            } catch (exception: Exception) {<br>                exception.message?.<em>let </em><strong>{<br>                    </strong>Log.d(LOG, <strong>it</strong>)<br>                <strong>}<br>            </strong>}<br>        <strong>}<br>    </strong>}<br>}</pre><ul><li>In order to call a Coroutines, we have to implement a CoroutineScope . This provides the scope in which the given Coroutines should send out its result. In this case, we will implement the MainScope() , which creates the scope for UI components.</li><li>val messageis observable (LiveData), which means that an observer is notified when the data held by the LiveData object changes.</li></ul><p><strong>Setting the View<br></strong>Our UI is pretty simple. Here is activity_main.xml :</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/imageViewDog&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;300dp&quot;<br>        android:layout_centerInParent=&quot;true&quot;<br>        android:src=&quot;@color/design_default_color_secondary&quot; /&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/randomDog&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_alignParentBottom=&quot;true&quot;<br>        android:text=&quot;Random Dog&quot; /&gt;<br><br>&lt;/RelativeLayout&gt;</pre><p>Our MainActivity class:</p><pre>class MainActivity : AppCompatActivity() {<br><br>    lateinit var viewModel: MainViewModel<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_main</em>)<br><br>        viewModel = ViewModelProvider(this).get(MainViewModel::class.<em>java</em>)<br><br>        viewModel.getRandomDog()<br><br>        randomDog.setOnClickListener <strong>{<br>            </strong>viewModel.getRandomDog()<br>        <strong>}<br><br>        </strong>viewModel.message.observe(<br>            this,<br>            <strong>{<br>                </strong>Glide.with(this)<br>                    .load(<strong>it</strong>)<br>                    .into(imageViewDog)<br>            <strong>}<br>        </strong>)<br>    }<br>}</pre><p>That’s all, our project is set up. Now, let’s run our project. You will be able to see a random puppy 🐶 every time you click the Random Dog button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*kYztFQ7XVmFJlaik6miCkw.jpeg" /></figure><h4>That is it for this article. Thank you so much for your time!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b0581951fcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>