0

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
emreturka
  • 846
  • 3
  • 18
  • 44
  • `flatMapConcat { flowOf( /*...*/) }` can be replaced with `map { /*...*/ }`, since you are creating a flow of only one emission. Not enough info is provided to understand exactly what you're doing with the if/else chain. We don't know the types involved. – Tenfour04 Sep 11 '22 at 01:16
  • I replaced flatMapConcat with map {}. Also here I have to write BaseResourceEvent extension. Not flow extension. I wrote a BaseResourceEvent extension and it clear up. Thanks for your response – emreturka Sep 11 '22 at 06:43

1 Answers1

0

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()
  }
}
emreturka
  • 846
  • 3
  • 18
  • 44