Skip to content

Commit

Permalink
Define QueueManager and Implement RealQueueManager
Browse files Browse the repository at this point in the history
Signed-off-by: mramotar <[email protected]>
  • Loading branch information
matt-ramotar committed Mar 16, 2024
1 parent c38c694 commit 4e2343b
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.mobilenativefoundation.paging.core.impl

import org.mobilenativefoundation.paging.core.PagingKey

/**
* Represents a manager for the queue of pages to be loaded.
*
* @param K The type of the key used for paging.
* @param P The type of the parameters associated with each page of data.
*/
interface QueueManager<K : Any, P : Any> {
/**
* Enqueues a page key to be loaded.
*
* @param key The [PagingKey] representing the page to be loaded.
*/
fun enqueue(key: PagingKey<K, P>)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package org.mobilenativefoundation.paging.core.impl

import kotlinx.coroutines.flow.StateFlow
import org.mobilenativefoundation.paging.core.FetchingStrategy
import org.mobilenativefoundation.paging.core.Logger
import org.mobilenativefoundation.paging.core.PagingAction
import org.mobilenativefoundation.paging.core.PagingBuffer
import org.mobilenativefoundation.paging.core.PagingConfig
import org.mobilenativefoundation.paging.core.PagingKey

class RealQueueManager<Id : Comparable<Id>, K : Any, P : Any, D : Any, E : Any, A : Any>(
pagingConfigInjector: Injector<PagingConfig>,
loggerInjector: OptionalInjector<Logger>,
dispatcherInjector: Injector<Dispatcher<Id, K, P, D, E, A>>,
private val fetchingStrategy: FetchingStrategy<Id, K, P, D>,
private val pagingBuffer: PagingBuffer<Id, K, P, D>,
private val anchorPosition: StateFlow<PagingKey<K, P>>,
private val stateManager: StateManager<Id, K, P, D, E>,
) : QueueManager<K, P> {

private val logger = lazy { loggerInjector.inject() }
private val pagingConfig = lazy { pagingConfigInjector.inject() }
private val dispatcher = lazy { dispatcherInjector.inject() }

private val queue: ArrayDeque<PagingKey<K, P>> = ArrayDeque()

override fun enqueue(key: PagingKey<K, P>) {
logger.value?.log(
"""
Enqueueing:
Key: $key
""".trimIndent()
)

queue.addLast(key)

processQueue()
}

private fun processQueue() {
while (queue.isNotEmpty() && fetchingStrategy.shouldFetch(
anchorPosition = anchorPosition.value,
prefetchPosition = stateManager.state.value.prefetchPosition,
pagingConfig = pagingConfig.value,
pagingBuffer = pagingBuffer,
)
) {
val nextKey = queue.removeFirst()

logger.value?.log(
"""Dequeued:
Key: $nextKey
""".trimMargin(),
)

dispatcher.value.dispatch(PagingAction.Load(nextKey))
}
}
}

0 comments on commit 4e2343b

Please sign in to comment.