<commit_before>package com.github.elifarley.kotlin.coroutines

import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.delay
import kotlin.coroutines.experimental.CoroutineContext

fun <T> delayWhile(
        predicate: T.() -> Boolean,
        maxDelayPerItem: Long = 30000L,
        context: CoroutineContext,
        block: suspend () -> T
): Deferred<T> = async(context) {
    val start = System.currentTimeMillis()
    var result : T?
    while (true) {
        result = block()
        println("[delayWhile] ${System.currentTimeMillis() - start} ms; Predicate: ${result?.predicate() ?: true}") // TODO Remove
        if (! (result?.predicate() ?: true)) break
        delay(Math.min(maxDelayPerItem, System.currentTimeMillis() - start))
    }
    result!!
}
<commit_msg>New parameter: maxElapsedTime<commit_after>package com.github.elifarley.kotlin.coroutines

import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.delay
import kotlin.coroutines.experimental.CoroutineContext

fun <T> delayWhile(
        context: CoroutineContext,
        predicate: (T.() -> Boolean) = {this == null},
        maxElapsedTime: Long = 2 * 60 * 1000,
        maxDelayPerIter: Long = 30000L,
        block: suspend () -> T
): Deferred<T> = async(context) {
    val start = System.currentTimeMillis()
    var result: T?
    while (true) {
        result = block()
        println("[delayWhile] ${System.currentTimeMillis() - start} ms; Predicate: ${result?.predicate() ?: true}") // TODO Remove
        if (!(result?.predicate() ?: true)) break
        if (System.currentTimeMillis() - start >= maxElapsedTime) {
            throw TimeoutException("Max elapsed time exceeded. Elapsed time: ${System.currentTimeMillis() - start}ms")
        }
        delay(Math.min(maxDelayPerIter, System.currentTimeMillis() - start))
    }
    result!!
}

{'fraction_non_alphanumeric': 0.1292929292929293, 'fraction_numerical': 0.008585858585858586, 'mean_word_length': 3.4417040358744395, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '978341', 'n_tokens_mistral': 621, 'n_tokens_neox': 607, 'n_words': 128}