Skip to content

How to express intersection of two CoroutineScopes? #814

@BoxResin

Description

@BoxResin

I want to use CoroutineScope that is only working when two Jobs are active.

Example

class Something : CoroutineScope {
    // onBind ~ onUnbind
	private var scopeJobBind = Job().apply { cancel() }

	// onResume ~ onPause
	private var scopeJobLifecycle = Job().apply { cancel() }

	// Intention: (onBind ~ onUnbind) ∩ (onResume ~ onPause)
	override val coroutineContext get() = Dispatchers.Main + scopeJobBind + scopeJobLifecycle // The problem: scopeJobLifecycle replaces scopeJobBind

	fun onBind() {
		scopeJobBind = Job()
	}

	fun onUnbind() {
		scopeJobBind.cancel()
	}

	fun onResume() {
		scopeJobLifecycle = Job()
	}

	fun onPause() {
		scopeJobLifecycle.cancel()
	}

	fun foo() {
		// It should be launched only when both scopeJobBind and scopeJobLifecycle are active.
		launch {
			...
		}
	}
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions