how to use coroutines with retrofit in MVVM architecture

Viewed 1359

I work on a project with retrofit and rxjava in MVVM architecture that contains a repository and repositoryImpl package. I want to remove rxjava and just use Kotlin coroutine for this project. but after search and read articles for migrating from rxjava to coroutine I did not found a right and clean way. may please help me to implement this section that implemented with rxjava implement with coroutines

MyProjectService.kt:

 @POST("/user/login")
fun login(@Body agentModel: AgentModel): Observable<APIResultModel<AgentModel>>

Repository.kt :

interface Repository {

fun login(
    context: Context,
    userModel: AgentModel,
    callback: (Result<APIResultModel<AgentModel>, RaakebException>) -> Unit

RepositoryImpl.kt :

class RepositoryImpl : Repository {


private val api = RaakebApi.instance

private val prefs by lazy {
    UserPreferences()
}


override fun login(
    context: Context,
    userModel: AgentModel,
    callback: (Result<APIResultModel<AgentModel>, RaakebException>) -> Unit
) {
    val error = showError(callback)

    val result = Consumer<APIResultModel<AgentModel>> { agent ->

        prefs.token = agent.apiObjects.token.toString()
        callback(Result.Success(agent))
    }

    val hashMap = HashMap<String, Any>()
    val deviceModel = DeviceModel()

    deviceModel.uniqueID = DeviceInfoHelper.getDeviceUniqueID(context)
    deviceModel.appVersion = DeviceInfoHelper.getAppVersion()
    deviceModel.platform = "ANDROID"
    deviceModel.sdkVersion = DeviceInfoHelper.getSDKVersion()
    deviceModel.phoneBrand = DeviceInfoHelper.getPhoneBrand()
    deviceModel.phoneModel = DeviceInfoHelper.getPhoneModel()
    //deviceModel.notificationID = Rakeeb.prefs.notification_id

    hashMap["user"] = userModel
    hashMap["device"] = deviceModel

    api.login(userModel)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(result, error)
}

I tried to make it but It's wrong. and I don't know how I must fix it.

MyProjectService.kt :

interface MyProjectService {

@POST("/user/login")
suspend fun login(@Body agentModel: AgentModel): Result<APIResultModel<AgentModel>, RaakebException>

companion object {

    private val prefs by lazy {
        UserPreferences()
    }

    val instance: RaakebApi by lazy {

        val builder = OkHttpClient.Builder()

        builder.addInterceptor {

            val requestBuilder = it.request().newBuilder()

            if (!it.request().url().url().path?.contains("/user/login")!!) {
                requestBuilder.addHeader("auth", prefs.token)
            }

            requestBuilder.addHeader("Content-Type", "application/json")
            it.proceed(requestBuilder.build())
        }

        builder.readTimeout(30, TimeUnit.SECONDS)
        builder.connectTimeout(30, TimeUnit.SECONDS)

        val client = builder.build()

        val retrofitBuilder: Retrofit.Builder = Retrofit.Builder()
            .client(client)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addCallAdapterFactory(CoroutineCallAdapterFactory())

        return@lazy retrofitBuilder.baseUrl(ConstHelper.SERVER_URL)
            .addConverterFactory(GsonConverterFactory.create()).build()
            .create(RaakebApi::class.java)
    }
}

}

Repository.kt :

interface Repository {

suspend fun login(
    context: Context,
    userModel: AgentModel
) : Result<APIResultModel<AgentModel>, RaakebException>
   companion object {
    val instance: Repository by lazy {
        RepositoryImpl()
    }
}

RepositoryImpl.kt :

class RepositoryImpl : Repository {


private val api = RaakebApi.instance

private val prefs by lazy {
    UserPreferences()
}


override suspend fun login(
    context: Context,
    userModel: AgentModel
): Result<APIResultModel<AgentModel>, RaakebException> = withContext(Dispatchers.IO) {

    when (val response = api.login(userModel)) {
        is Result.Success -> {

           /* val hashMap = HashMap<String, Any>()
            val deviceModel = DeviceModel()

            deviceModel.uniqueID = DeviceInfoHelper.getDeviceUniqueID(context)
            deviceModel.appVersion = DeviceInfoHelper.getAppVersion()
            deviceModel.platform = "ANDROID"
            deviceModel.sdkVersion = DeviceInfoHelper.getSDKVersion()
            deviceModel.phoneBrand = DeviceInfoHelper.getPhoneBrand()
            deviceModel.phoneModel = DeviceInfoHelper.getPhoneModel()
            //deviceModel.notificationID = Rakeeb.prefs.notification_id

            hashMap["user"] = userModel
            hashMap["device"] = deviceModel*/
            return@withContext response.success
        }
        is Result.Error -> {

        }
    }
}

thanks for your help.

1 Answers

You can return from a retrofit api function your type with "suspend" keyword. If you want to remove rx Observables from repositories. But you need to remember: "coroutine = Single". You can't use it like Flowable. If you want I can share my project for you. I've changed rx to coroutines there.

Related