UndercoverGeek
UndercoverGeek

Reputation: 37

Is there a alternative in Kotlin coroutines for RxJava's 'Single'?

I am trying to convert some RxJava code to use coroutines instead.

Here is an example of code to make an API call using Single in RxJava. What do I need to do to replicate that part of the functionality using coroutines?

 override fun getRegisteredDevicesList(
        headerStoreId: String,
        headerDeviceId: String,
        headerApplicationVersionNo: String,
        appId: String,
        storeId: String
    ): Single<Result<RegisteredDevicesListData>> {

        return deviceLocatorApiService.getRegisteredDevicesListFromServer(
            headerStoreId = headerStoreId,
            headerDeviceId = headerDeviceId,
            headerApplicationVersionNo = headerApplicationVersionNo,
            registeredDevicesListRequest = RegisteredDevicesListRequest(
                appId = appId,
                storeId = storeId
            )
        )
            .map { Result.withValue(it.toDomain()) }
            .onErrorReturn {
                Result.withError(
                    DeviceLocatorError(Utility.getNetworkErrorMessageFromThrowable(it), it)
                )
            }
    }

Someone suggested that I use coroutineScopes, but I'm struggling to implement it.

Upvotes: 1

Views: 1832

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 199805

Kotlin publishes a number of Coroutines for reactive streams libraries that already provide helper methods for converting RxJava code into coroutines code such as an await method that transforms a Single into a suspending function (which is the equivalent in coroutines):

suspend fun getRegisteredDevicesListSuspending(
  headerStoreId: String,
  headerDeviceId: String,
  headerApplicationVersionNo: String,
  appId: String,
  storeId: String
): Result<RegisteredDevicesListData> {
  return getRegisteredDevicesList(
    headerStoreId,
    headerDeviceId,
    headerApplicationVersionNo,
    appId,
    storeId
  ).await() // Transforms your Single into a suspending method
}

Of course, if you want to go deeper and avoid usages of RxJava entirely, you can also use APIs like suspendCancellableCoroutine to convert a callback based API directly into coroutines as explained in this blog post.

Upvotes: 2

Related Questions