Skip to content

Instantly share code, notes, and snippets.

@rubenpla-develop
Last active May 23, 2019 01:38
Show Gist options
  • Save rubenpla-develop/343d53d717f223275317e9aded01066f to your computer and use it in GitHub Desktop.
Save rubenpla-develop/343d53d717f223275317e9aded01066f to your computer and use it in GitHub Desktop.
#Kotlin #Android Retrofit2 singleton instance sample
package rubenpla.develop.privtmdbendlesslist.data.api
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import rubenpla.develop.privtmdbendlesslist.data.model.MoviesResultsItem
interface TmdbApi {
@GET("movie/popular")
fun getPopularMovies(@Query("api_key") api_key: String,
@Query("page") page: Int): List<MoviesResultsItem>
companion object Factory {
@Volatile
private var retrofit : Retrofit? = null
private const val BASE_URL: String = "https://api.themoviedb.org/3/"
@Synchronized
fun getInstance(): TmdbApi? {
retrofit ?: synchronized(this) {
retrofit ?: buildRetrofit()
}
return retrofit?.create(TmdbApi::class.java)
}
private fun buildRetrofit() = retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
@tomjegan
Copy link

tomjegan commented Jan 4, 2019

Should line 26 be:

retrofit ?: buildRetrofit()

@rayzone107
Copy link

Line 26 would be

retrofit = buildRetrofit()

instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment