fun {{ setter.receiver }}.{{ setter.methodName }}Listener(
        context: {{ imported("kotlin.coroutines.CoroutineContext") }} = {{ imported("kotlinx.coroutines.Dispatchers.Main") }},
        init: {{ setter.listener }}.() -> Unit
) {
    val listener = {{ setter.listener }}(context)
    listener.init()
    {{ setter.setter }}(listener)
}

class {{ helperClassName }}(private val context: {{ imported("kotlin.coroutines.CoroutineContext") }}) : {{ listenerClassName }}{{ superConstructorCall }} {
{% for method in methods %}
    private var _{{ method.varName }}: (suspend {{ imported("kotlinx.coroutines.CoroutineScope") }}.({{ method.argTypes }}) -> {{ imported(method.returnType) }})? = null
    {% if (method.returnType != "Unit") %}private var _{{ method.varName }}_returnValue: {{ method.possiblyNullableReturnType }}{% if (method.returnDefaultValue != "") %} = {{ method.returnDefaultValue }}{% endif %}{% endif %}

    override fun {{ method.methodName }}({{ method.args }}){% if (method.returnType != "Unit") %} : {{ method.returnType }}{% endif %} {
        {% if (method.returnType != "Unit") %}val returnValue = _{{ method.varName }}_returnValue
        {% endif %}val handler = _{{ method.varName }} ?: return{% if (method.returnType != "Unit") %} returnValue{% endif %}
        {% if (method.hasArgs == true) -%}
        {{ imported("kotlinx.coroutines.GlobalScope") }}.{{ imported("kotlinx.coroutines.launch") }}(context) {
            handler({{ method.argNames }})
        }
        {%- else -%}
        {{ imported("kotlinx.coroutines.GlobalScope") }}.{{ imported("kotlinx.coroutines.launch") }}(context, block = handler)
        {%- endif %}{% if (method.returnType != "Unit") %}
        return returnValue{% endif %}
    }

    fun {{ method.methodName }}(
            {% if (method.returnType != "Unit") %}returnValue: {{ method.returnType }}{% if (method.returnDefaultValue != "") %} = {{ method.returnDefaultValue }}{% endif %},
            {% endif %}listener: suspend {{ imported("kotlinx.coroutines.CoroutineScope") }}.({{ method.argTypes }}) -> {{ imported(method.returnType) }}
    ) {
        _{{ method.varName }} = listener{% if (method.returnType != "Unit") %}
        _{{ method.varName }}_returnValue = returnValue{% endif %}
    }
{% endfor %}
}