flatMapConcat for convert

208 Views Asked by At

I have a flow that return my event type generic like
Flow<BaseResourceEvent<T>> But sometimes I have to convert T type to another type. For example User type to DashBoardUser with an extension function like below;

fun User.toDashBoardUser(): DashBoardUser {
  return DashBoardUser(
    nameSurname = this.name+" "+this.surname,
    pic = this.picture
 )
}

I am doing flow concantation like below;

return serviceCall {
        kullaniciRepository.getKullaniciBilgiByAPI()
    }.flatMapConcat {
        flowOf(
            if (it is BaseResourceEvent.Success)
                BaseResourceEvent.Success(data = it.data!!.toDashBoardKullaniciBilgi())
            else if (it is BaseResourceEvent.Error) {
                BaseResourceEvent.Error(message = it.message)
            } else {
                BaseResourceEvent.Loading()
            }
        )
    }.flowOn(ioDispatcher)

This code is reason to boilerprate. How to write an extension for this process.

1

There are 1 best solutions below

0
emreturka On

I have solved the problem thereby write an extension function to BaseResourceEvent like below;

 fun <R, C> BaseResourceEvent<R>.convertRersourceEventType(
   onSuccess:(() -> Unit)? = null,
   convert: () -> C,
 ): BaseResourceEvent<C> {
return if (this is BaseResourceEvent.Success) {
    onSuccess?.let {
        it.invoke()
    }
    BaseResourceEvent.Success(data = convert.invoke())
  }else if (this is BaseResourceEvent.Error) {
    BaseResourceEvent.Error(message = this.message)
  } else {
    BaseResourceEvent.Loading()
  }
}