-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(kotlin): add browse helpers (#4059)
- Loading branch information
Showing
3 changed files
with
154 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
41 changes: 41 additions & 0 deletions
41
...nt-kotlin/client/src/commonMain/kotlin/com/algolia/client/extensions/internal/Iterable.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
package com.algolia.client.extensions.internal | ||
|
||
import com.algolia.client.exception.AlgoliaIterableException | ||
import kotlinx.coroutines.delay | ||
import kotlin.time.Duration | ||
|
||
public data class IterableError<T>( | ||
public val validate: (T) -> Boolean, | ||
public val message: ((T) -> String)? = null | ||
) | ||
|
||
public suspend fun <T> createIterable( | ||
execute: suspend (T?) -> T, | ||
validate: (T) -> Boolean, | ||
aggregator: ((T) -> Unit)? = null, | ||
timeout: () -> Duration = { Duration.ZERO }, | ||
error: IterableError<T>? = null | ||
): T { | ||
suspend fun executor(previousResponse: T? = null): T { | ||
val response = execute(previousResponse) | ||
|
||
if (aggregator != null) { | ||
aggregator(response) | ||
} | ||
|
||
if (validate(response)) { | ||
return response | ||
} | ||
|
||
if (error != null && error.validate(response)) { | ||
val message = error.message?.invoke(response) ?: "An error occurred" | ||
throw AlgoliaIterableException(message) | ||
} | ||
|
||
delay(timeout().inWholeMilliseconds) | ||
|
||
return executor(response) | ||
} | ||
|
||
return executor() | ||
} |