'Pagination on Android jetpack compose LazyColumn
I am developing an Android Chat App using jetpack compose.
The chat messages are coming from WebSocket. (I use OkHttp library)
And all of the messages should be stored in the local database (I use Room)
When a user scrolls to the top, the app tries to get the messages from the local database. If the local database has no data, it tries to get the messages from the Remote API server.
And this logic is implemented by the Repository pattern.
class ChatMessageRepository (
private val localMessageDao: LocalMessageDao,
private val remoteApiServer: RemoteApiServer
) {
fun getMessages(offset: Int) {
val cachedMessages = localMessageDao.get(offset)
if (cachedMessages.isNotEmpty()) {
return cachedMessages
}
return remoteApiServer.getMessages(offset)
.also {
localMessageDao.insert(it)
}
}
}
And I can integrate this with the PagingSource.
class ChatPagingSource(
private val repo: ChatMessageRepository
): PagingSource<Int, Chat>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Chat> {
val offset = params.key ?: 1
val messages = repo.getMessages(offset)
return LoadResult.Page(
data = messages ,
prevKey = if (offset == 1) null else offset - messages .size,
nextKey = null
)
}
}
But the problem is that I don't know how can I integrate the WebSocket data stream with PagingSource.
class WebSocketService: WebSocketListener() {
val messageSubject: PublishSubject<WsMsg> = PublishSubject.create()
override fun onMessage(webSocket: WebSocket, text: String) {
super.onMessage(webSocket, text)
messageSubject.onNext(friendStatus)
}
}
I am receiving the chat message using the OkHttp library callback method.
How can I do this?
Should I give up to use Paging library, and just develop using LazyColumn scroll detect?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
