All Projects → navi25 → Retrofitkotlindeferred

navi25 / Retrofitkotlindeferred

Licence: mit
Android Networking using Retrofit2, Kotlin and its Deferred Type

Programming Languages

kotlin
9241 projects

Projects that are alternatives of or similar to Retrofitkotlindeferred

Mifos Mobile
Repository for the Mifos Mobile Banking App for clients
Stars: ✭ 154 (-3.75%)
Mutual labels:  okhttp3, retrofit2
Spider
Monitor and modify network requests
Stars: ✭ 78 (-51.25%)
Mutual labels:  okhttp3, retrofit2
Pokemongo
神奇宝贝 (PokemonGo) 基于 Jetpack + MVVM + Repository 设计模式 + Data Mapper + Kotlin Flow 的实战项目,如果这个仓库对你有帮助,请仓库右上角帮我 star 一下,非常感谢。
Stars: ✭ 848 (+430%)
Mutual labels:  okhttp3, retrofit2
Nice Knowledge System
📚不积跬步无以至千里,每天进步一点点,Passion,Self-regulation,Love and Share
Stars: ✭ 137 (-14.37%)
Mutual labels:  okhttp3, retrofit2
Retrofiturlmanager
🔮 Let Retrofit support multiple baseUrl and can be change the baseUrl at runtime (以最简洁的 Api 让 Retrofit 同时支持多个 BaseUrl 以及动态改变 BaseUrl).
Stars: ✭ 1,961 (+1125.63%)
Mutual labels:  okhttp3, retrofit2
Bilisoleil
An unofficial bilibili client for android --rxjava2+mvp+okhttp3+retrofit2+dagger2
Stars: ✭ 430 (+168.75%)
Mutual labels:  okhttp3, retrofit2
Todo List
待办事项APP
Stars: ✭ 45 (-71.87%)
Mutual labels:  okhttp3, retrofit2
Moviehub
Showcases popular movies, tv shows, and people from The Movie Database
Stars: ✭ 325 (+103.13%)
Mutual labels:  okhttp3, retrofit2
Rxapp
Stars: ✭ 108 (-32.5%)
Mutual labels:  okhttp3, retrofit2
Todo
简洁清爽的Todo清单工具❤️ (MVP+okhttp3+retrofit+gson)
Stars: ✭ 93 (-41.87%)
Mutual labels:  okhttp3, retrofit2
Mvvmarms
Android MVVM Architecture Components based on MVPArms and Android Architecture Components.
Stars: ✭ 425 (+165.63%)
Mutual labels:  okhttp3, retrofit2
Androidstarter
A sample Android app using the MVP architecture.
Stars: ✭ 140 (-12.5%)
Mutual labels:  okhttp3, retrofit2
Wanandroid
🏄 基于Architecture Components dependencies (Lifecycles,LiveData,ViewModel,Room)构建的WanAndroid开源项目。 你值得拥有的MVVM快速开发框架:https://github.com/jenly1314/MVVMFrame
Stars: ✭ 410 (+156.25%)
Mutual labels:  okhttp3, retrofit2
Bilibili Android Client
An unofficial bilibili client for android http://www.jianshu.com/p/f69a55b94c05 -- 该项目已停止维护!
Stars: ✭ 4,430 (+2668.75%)
Mutual labels:  okhttp3, retrofit2
Androidproject
Android 技术中台,但愿人长久,搬砖不再有
Stars: ✭ 4,398 (+2648.75%)
Mutual labels:  okhttp3, retrofit2
Heyyoo
Heyyoo is a sample social media Android application 📱 built to demonstrate use of Modern Android development tools - (Kotlin, Coroutines, Architecture Components, MVVM, Room, Retrofit, Material Components).
Stars: ✭ 38 (-76.25%)
Mutual labels:  okhttp3, retrofit2
Crazydaily
[开源项目] 一款程序员日常放松的App,基于Material Design + MVP-Clean + Weex + Flutter + RxJava2 + Retrofit + Dagger2 + Glide + Okhttp + MTRVA + BRVAH + 炫酷控件 + 炫酷动画
Stars: ✭ 294 (+83.75%)
Mutual labels:  okhttp3, retrofit2
Jetpack github
基于Kotlin + Jetpack全家桶 + Coroutines(协程) + Flutter等架构实现的一款精简版Github客户端项目,望与广大小伙伴一起成长,欢迎start or fork!
Stars: ✭ 314 (+96.25%)
Mutual labels:  okhttp3, retrofit2
Newspaper
An aggregated newspaper app containing news from 10+ local news publishers in Hong Kong. Made with ❤
Stars: ✭ 82 (-48.75%)
Mutual labels:  okhttp3, retrofit2
Android Cnblogs
🔥🔥 博客园Android端开源项目,界面简洁清新。
Stars: ✭ 127 (-20.62%)
Mutual labels:  okhttp3, retrofit2

RetrofitKotlinDeferred

Simple to Complex Tutorial for making network calls in Android using Retrofit2, Kotlin and its Deferred Type

For detailed explanation of code, visit here.

Index

Dependencies

Add the following to the App dependencies

// build.gradle(Module: app)
dependencies {

    def moshiVersion="1.8.0"
    def retrofit2_version = "2.5.0"
    def okhttp3_version = "3.12.0"
    def kotlinCoroutineVersion = "1.0.1"

     
    //Moshi
    implementation "com.squareup.moshi:moshi-kotlin:$moshiVersion"
    kapt "com.squareup.moshi:moshi-kotlin-codegen:$moshiVersion"

    //Retrofit2
    implementation "com.squareup.retrofit2:retrofit:$retrofit2_version"
    implementation "com.squareup.retrofit2:converter-moshi:$retrofit2_version"
    implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2"

    //Okhttp3
    implementation "com.squareup.okhttp3:okhttp:$okhttp3_version"
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'

    //Kotlin Coroutines
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlinCoroutineVersion"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinCoroutineVersion"

    //Picasso for Image Loading
    implementation ('com.squareup.picasso:picasso:2.71828'){
        exclude group: "com.android.support"
    }
}

API #1 : JSONPlaceHolder API

A Fake Online REST API for Testing and Prototyping

JSONPlaceholder comes with a set of 6 common resources:

A simple example

Global Setup

//ApiFactory to create jsonPlaceHolder Api
object Apifactory{
    fun retrofit() : Retrofit = Retrofit.Builder()
                .client(OkHttpClient().newBuilder().build())
                .baseUrl("https://jsonplaceholder.typicode.com")
                .addConverterFactory(MoshiConverterFactory.create())
                .addCallAdapterFactory(CoroutineCallAdapterFactory())
                .build()   

    val placeHolderApi : PlaceholderApi = retrofit().create(PlaceholderApi::class.java)
} 

Fetching Posts from /posts

//Data Model for Post
data class PlaceholderPosts(
    val id: Int,
    val userId : Int,
    val title: String,
    val body: String
)

//A retrofit Network Interface for the Api
interface PlaceholderApi{
    @GET("/posts")
    fun getPosts() : Deferred<Response<List<PlaceholderPosts>>>
}

//Finally making the call
val service = ApiFactory.placeholderApi
GlobalScope.launch(Dispatchers.Main) {
    val postRequest = service.getPosts() // Making Network call
    try {
        val response = postRequest.await()
        val posts = response.body() // This is List<PlaceholderPosts> 
    }catch (e: Exception){

    }
}

Fetching Users from /users

Data Model for user

// Data model for user
data class PlaceholderUsers(
    val id:Int,
    val name: String,
    val username: String,
    val email: String,
    val address: PlaceholderAddress,
    val phone: String,
    val website: String,
    val company: PlaceholderCompany
)

/**
 * Helper data classes for PlaceholderUsers
 */
data class PlaceholderAddress(
    val street: String,
    val suite: String,
    val city: String,
    val zipcode: String,
    val geo: PlaceholderGeo
)

data class PlaceholderGeo(
    val lat: String,
    val lng: String
)

data class PlaceholderCompany(
    val name: String,
    val catchPhrase: String,
    val bs: String
)

Api call for User

interface PlaceholderApi{
    @GET("/posts")
    fun getPosts() : Deferred<Response<List<PlaceholderPosts>>>

    @GET("/users")
    fun getUsers() : Deferred<Response<List<PlaceholderUsers>>>
}

//Getting Users from Jsonplaceholder API
GlobalScope.launch(Dispatchers.Main) {
    val userRequest = service.getUsers()
    try {
        val response = userRequest.await()
        val users = response.body() // This is List<PlaceholderUsers>

    }catch (e: Exception){

    }
}

API #2 : TMDB API

The Movie Database (TMDb) API - It contains list of all popular, upcoming, latest, now showing etc movie and tv shows. This is one of the most popular API to play with too.

TMDB api requires an Api key to make requests.

Hiding API key in Version Control (Optional but Recommended)

Once you have Api key, do the following steps to hide it in VCS.

  • Add your key in local.properties present in root folder.
  • Get access to the key in build.gradle programmatically.
  • Then the key is available to you in the program though BuildConfig.
//In local.properties
tmdb_api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxx"

//In build.gradle (Module: app)
buildTypes {
    Properties properties = new Properties()
    properties.load(project.rootProject.file("local.properties").newDataInputStream())
    def tmdbApiKey = properties.getProperty("tmdb_api_key", "")

    debug {
        buildConfigField 'String', "TMDB_API_KEY", tmdbApiKey
        resValue 'string', "api_key", tmdbApiKey
    }

    release {
        buildConfigField 'String', "TMDB_API_KEY", tmdbApiKey
        resValue 'string', "api_key", tmdbApiKey
    }
}

//In your Constants File
var tmdbApiKey = BuildConfig.TMDB_API_KEY

A Simple Example

Global Setup

//ApiFactory to create jsonPlaceHolder Api
object Apifactory{
    fun retrofit() : Retrofit = Retrofit.Builder()
                .client(OkHttpClient().newBuilder().build())
                .baseUrl("https://api.themoviedb.org/3/")
                .addConverterFactory(MoshiConverterFactory.create())
                .addCallAdapterFactory(CoroutineCallAdapterFactory())
                .build()   

   val tmdbApi : TmdbApi = retrofit().create(TmdbApi::class.java)
} 

Fetching Popular movies from Endpoint : /movie/popular

// Data Model for TMDB Movie item
data class TmdbMovie(
    val id: Int,
    val vote_average: Double,
    val title: String,
    val overview: String,
    val adult: Boolean
)

// Data Model for the Response returned from the TMDB Api
data class TmdbMovieResponse(
    val results: List<TmdbMovie>
)

//A retrofit Network Interface for the Api
interface TmdbApi{
    @GET("movie/popular")
    fun getPopularMovie(): Deferred<Response<TmdbMovieResponse>>
}

//Finally making the call
val movieService = ApiFactory.tmdbApi
GlobalScope.launch(Dispatchers.Main) {
    val popularMovieRequest = movieService.getPopularMovie()
    try {
        val response = popularMovieRequest.await()
        val movieResponse = response.body() //This is single object Tmdb Movie response
        val popularMovies = movieResponse?.results // This is list of TMDB Movie
    }catch (e: Exception){

    }
}

Example Project

This project is filled with these examples. Clone it, add your API key in the local.properties and check out the implementation.

Happy Coding!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].