Hi, there this block is still asking for a return...
# android
a
Hi, there this block is still asking for a return statement, though i'm only able to return from the 'fold' block, any way out of it ?
Copy code
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Hotel> {
    val currentPage = params.key ?: pageSetting.page
    hotelSearchRepository.search(
        hotelInquiry,
        page = currentPage,
        itemsPerPage = pageSetting.records
    ).collect { result ->
>>>>>     return@collect  result.fold(onSuccess = { hotelInquiryDetails ->
            Page(
                data = hotelInquiryDetails.hotels,
                prevKey = if (currentPage == STARTING_PAGE_INDEX) null else (currentPage - 1),
                nextKey = if (hotelInquiryDetails.hotels.isEmpty()) null else (currentPage + pageSetting.records)
            )
        }, onFailure = {
            Error<Int, Hotel>(Exception(it))
        })
    }
} <<<<< - Error not return statement
g
You cannot return from callback of course
1
You need different API which will suspend until result, essentially you just need Flow.first()
Copy code
val result = hotelSearchRepository.search(...).first()
1
So it’s exactly use case for coroutines, convert callback to code which looks as blocking code
1
Another way is do not use flow on hotelSearchRepository.search at all, it doesn’t look as API which is good for using Flow, it probably always has only one result
1
If hotelSearchRepository.search() would be a suspend function, it would be probably easier to think about it, though with adapters from suspend function to Flow and from Flow to suspend function it’s very easy to convert between different styles, just keep in mind that Flow may have 0-infinite amount of values and suspend function exactly 1
a
hmm, kotlin flow it self has soo much subtle points to to be kept in mind. This subject, it self require some amount of mastery, to properly tame and use it ... novice can get lost sooner ... unfortunately we have to keep up with the industry too. Thank you @gildor for insightful answers you you have given. 🙂
g
flow it self has soo much subtle points to to be kept in mind
Well, yes, flow is abstraction for Reactive Streams, not only kotlin flow, it’s very similar to RxJava, Reactor etc So if you have stream of data/events it’s perfect abstraction for it, but encoding one time-events is not the best, it adds too much complexity and I would recommend to use suspend functions as soon as it enough for your use case
👍 1