Before starting this tutorial, I recommend you to read about Pagination Library in Android.

Here, we are going to implement pagination for fetching user photos from Instagram using the MVVM pattern. Let’s start now.

1. Configuration

To configure pagination in our project use

dependencies {
	  def paging_version = "2.1.2"

	  implementation "androidx.paging:paging-runtime:$paging_version"
	  }

for integrating Instagram please follow these steps.

Go to the next step when you have the required access token for Instagram.

2. Setting up network calls

  • Setting up Retrofit client
@Singleton
	class RetrofitClientInstagram @Inject constructor() {
	    val graphApiInterface: RetroApiInterface? by lazy {
	        getGraphApiClient()
	    }
	   private val okClient = OkHttpClient.Builder()
	            .addNetworkInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS).setLevel(HttpLoggingInterceptor.Level.BODY))
	            .build()

	    private fun getGraphApiClient(): RetroApiInterface {
	        val client = Retrofit.Builder()
	                .baseUrl("https://graph.instagram.com/")
	                .client(okClient)
	                .addConverterFactory(GsonConverterFactory.create())
	                .build()
	        return client.create(RetroApiInterface::class.java)
	    }

	}

	interface RetroApiInterface {

	    @GET("me/media")
	    fun getMediaList(@Query("access_token") token:String, @Query("fields") field:String, @Query("after") after:String? ): Call<InstagramMediaModel>

	}
  • Creating our media model
data class InstagramMediaModel(
	        var data: List<Data?>?,
	        var paging: Paging?
	) {
	    data class Data(
	            var id: String?,
	            var media_type: String?,
	            var media_url: Any?,
	            var children: Children?
	    )

	    data class Children(
	            var data: List<Data?>?
	    )

	    data class Paging(
	            var cursors: Cursors?,
	            var next: String?
	    ) {
	        data class Cursors(
	                var after: String?,
	                var before: String?
	        )
	    }
	}

#mvvm #kotlin #android

Implementing Pagination for fetching Instagram photos
4.80 GEEK