docs/topics/select-expression.md (2023)

Select expression makes it possible to await multiple suspending functions simultaneously and select the first one that becomes available.

Select expressions are an experimental feature of kotlinx.coroutines. Their API is expected to evolve in the upcoming updates of the kotlinx.coroutines library with potentially breaking changes.

{type=“note”}

Selecting from channels

Let us have two producers of strings: fizz and buzz. The fizz produces “Fizz” string every 300 ms:

fun CoroutineScope.fizz() = produce<String> { while (true) { // sends "Fizz" every 300 ms delay(300) send("Fizz") }}

And the buzz produces “Buzz!” string every 500 ms:

fun CoroutineScope.buzz() = produce<String> { while (true) { // sends "Buzz!" every 500 ms delay(500) send("Buzz!") }}

Using receive suspending function we can receive either from one channel or the other. But select expression allows us to receive from both simultaneously using its onReceive clauses:

(Video) Empathy: The Human Connection to Patient Care

suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) { select<Unit> { // <Unit> means that this select expression does not produce any result  fizz.onReceive { value -> // this is the first select clause println("fizz -> '$value'") } buzz.onReceive { value -> // this is the second select clause println("buzz -> '$value'") } }}

Let us run it all seven times:

import kotlinx.coroutines.*import kotlinx.coroutines.channels.*import kotlinx.coroutines.selects.*fun CoroutineScope.fizz() = produce<String> { while (true) { // sends "Fizz" every 300 ms delay(300) send("Fizz") }}fun CoroutineScope.buzz() = produce<String> { while (true) { // sends "Buzz!" every 500 ms delay(500) send("Buzz!") }}suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) { select<Unit> { // <Unit> means that this select expression does not produce any result  fizz.onReceive { value -> // this is the first select clause println("fizz -> '$value'") } buzz.onReceive { value -> // this is the second select clause println("buzz -> '$value'") } }}fun main() = runBlocking<Unit> {//sampleStart val fizz = fizz() val buzz = buzz() repeat(7) { selectFizzBuzz(fizz, buzz) } coroutineContext.cancelChildren() // cancel fizz & buzz coroutines//sampleEnd }

{kotlin-runnable=“true” kotlin-min-compiler-version=“1.3”}

You can get the full code here.

{type=“note”}

The result of this code is:

fizz -> 'Fizz'buzz -> 'Buzz!'fizz -> 'Fizz'fizz -> 'Fizz'buzz -> 'Buzz!'fizz -> 'Fizz'buzz -> 'Buzz!'

Selecting on close

The onReceive clause in select fails when the channel is closed causing the corresponding select to throw an exception. We can use onReceiveCatching clause to perform a specific action when the channel is closed. The following example also shows that select is an expression that returns the result of its selected clause:

suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String = select<String> { a.onReceiveCatching { it -> val value = it.getOrNull() if (value != null) { "a -> '$value'" } else { "Channel 'a' is closed" } } b.onReceiveCatching { it -> val value = it.getOrNull() if (value != null) { "b -> '$value'" } else { "Channel 'b' is closed" } } }

Let's use it with channel a that produces “Hello” string four times and channel b that produces “World” four times:

import kotlinx.coroutines.*import kotlinx.coroutines.channels.*import kotlinx.coroutines.selects.*suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String = select<String> { a.onReceiveCatching { it -> val value = it.getOrNull() if (value != null) { "a -> '$value'" } else { "Channel 'a' is closed" } } b.onReceiveCatching { it -> val value = it.getOrNull() if (value != null) { "b -> '$value'" } else { "Channel 'b' is closed" } } } fun main() = runBlocking<Unit> {//sampleStart val a = produce<String> { repeat(4) { send("Hello $it") } } val b = produce<String> { repeat(4) { send("World $it") } } repeat(8) { // print first eight results println(selectAorB(a, b)) } coroutineContext.cancelChildren() //sampleEnd } 

{kotlin-runnable=“true” kotlin-min-compiler-version=“1.3”}

(Video) CALI LOVES HER DADDY! SPECIAL BOND & A SWEET LETTER FROM A FATHER

You can get the full code here.

{type=“note”}

The result of this code is quite interesting, so we'll analyze it in more detail:

a -> 'Hello 0'a -> 'Hello 1'b -> 'World 0'a -> 'Hello 2'a -> 'Hello 3'b -> 'World 1'Channel 'a' is closedChannel 'a' is closed

There are a couple of observations to make out of it.

First of all, select is biased to the first clause. When several clauses are selectable at the same time, the first one among them gets selected. Here, both channels are constantly producing strings, so a channel, being the first clause in select, wins. However, because we are using unbuffered channel, the a gets suspended from time to time on its send invocation and gives a chance for b to send, too.

The second observation, is that onReceiveCatching gets immediately selected when the channel is already closed.

Selecting to send

Select expression has onSend clause that can be used for a great good in combination with a biased nature of selection.

Let us write an example of a producer of integers that sends its values to a side channel when the consumers on its primary channel cannot keep up with it:

(Video) Do Creationists Intentionally Deceive their Audience?

fun CoroutineScope.produceNumbers(side: SendChannel<Int>) = produce<Int> { for (num in 1..10) { // produce 10 numbers from 1 to 10 delay(100) // every 100 ms select<Unit> { onSend(num) {} // Send to the primary channel side.onSend(num) {} // or to the side channel  } }}

Consumer is going to be quite slow, taking 250 ms to process each number:

import kotlinx.coroutines.*import kotlinx.coroutines.channels.*import kotlinx.coroutines.selects.*fun CoroutineScope.produceNumbers(side: SendChannel<Int>) = produce<Int> { for (num in 1..10) { // produce 10 numbers from 1 to 10 delay(100) // every 100 ms select<Unit> { onSend(num) {} // Send to the primary channel side.onSend(num) {} // or to the side channel  } }}fun main() = runBlocking<Unit> {//sampleStart val side = Channel<Int>() // allocate side channel launch { // this is a very fast consumer for the side channel side.consumeEach { println("Side channel has $it") } } produceNumbers(side).consumeEach { println("Consuming $it") delay(250) // let us digest the consumed number properly, do not hurry } println("Done consuming") coroutineContext.cancelChildren() //sampleEnd }

{kotlin-runnable=“true” kotlin-min-compiler-version=“1.3”}

You can get the full code here.

{type=“note”}

So let us see what happens:

Consuming 1Side channel has 2Side channel has 3Consuming 4Side channel has 5Side channel has 6Consuming 7Side channel has 8Side channel has 9Consuming 10Done consuming

Selecting deferred values

Deferred values can be selected using onAwait clause. Let us start with an async function that returns a deferred string value after a random delay:

fun CoroutineScope.asyncString(time: Int) = async { delay(time.toLong()) "Waited for $time ms"}

Let us start a dozen of them with a random delay.

fun CoroutineScope.asyncStringsList(): List<Deferred<String>> { val random = Random(3) return List(12) { asyncString(random.nextInt(1000)) }}

Now the main function awaits for the first of them to complete and counts the number of deferred values that are still active. Note that we've used here the fact that select expression is a Kotlin DSL, so we can provide clauses for it using an arbitrary code. In this case we iterate over a list of deferred values to provide onAwait clause for each deferred value.

(Video) California Hair Stylist Sets Client's Hair on Fire to Get Rid of Split Ends

import kotlinx.coroutines.*import kotlinx.coroutines.selects.*import java.util.* fun CoroutineScope.asyncString(time: Int) = async { delay(time.toLong()) "Waited for $time ms"}fun CoroutineScope.asyncStringsList(): List<Deferred<String>> { val random = Random(3) return List(12) { asyncString(random.nextInt(1000)) }}fun main() = runBlocking<Unit> {//sampleStart val list = asyncStringsList() val result = select<String> { list.withIndex().forEach { (index, deferred) -> deferred.onAwait { answer -> "Deferred $index produced answer '$answer'" } } } println(result) val countActive = list.count { it.isActive } println("$countActive coroutines are still active")//sampleEnd}

{kotlin-runnable=“true” kotlin-min-compiler-version=“1.3”}

You can get the full code here.

{type=“note”}

The output is:

Deferred 4 produced answer 'Waited for 128 ms'11 coroutines are still active

Switch over a channel of deferred values

Let us write a channel producer function that consumes a channel of deferred string values, waits for each received deferred value, but only until the next deferred value comes over or the channel is closed. This example puts together onReceiveCatching and onAwait clauses in the same select:

fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> { var current = input.receive() // start with first received deferred value while (isActive) { // loop while not cancelled/closed val next = select<Deferred<String>?> { // return next deferred value from this select or null input.onReceiveCatching { update -> update.getOrNull() } current.onAwait { value -> send(value) // send value that current deferred has produced input.receiveCatching().getOrNull() // and use the next deferred from the input channel } } if (next == null) { println("Channel was closed") break // out of loop } else { current = next } }}

To test it, we'll use a simple async function that resolves to a specified string after a specified time:

fun CoroutineScope.asyncString(str: String, time: Long) = async { delay(time) str}

The main function just launches a coroutine to print results of switchMapDeferreds and sends some test data to it:

import kotlinx.coroutines.*import kotlinx.coroutines.channels.*import kotlinx.coroutines.selects.* fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> { var current = input.receive() // start with first received deferred value while (isActive) { // loop while not cancelled/closed val next = select<Deferred<String>?> { // return next deferred value from this select or null input.onReceiveCatching { update -> update.getOrNull() } current.onAwait { value -> send(value) // send value that current deferred has produced input.receiveCatching().getOrNull() // and use the next deferred from the input channel } } if (next == null) { println("Channel was closed") break // out of loop } else { current = next } }}fun CoroutineScope.asyncString(str: String, time: Long) = async { delay(time) str}fun main() = runBlocking<Unit> {//sampleStart val chan = Channel<Deferred<String>>() // the channel for test launch { // launch printing coroutine for (s in switchMapDeferreds(chan)) println(s) // print each received string } chan.send(asyncString("BEGIN", 100)) delay(200) // enough time for "BEGIN" to be produced chan.send(asyncString("Slow", 500)) delay(100) // not enough time to produce slow chan.send(asyncString("Replace", 100)) delay(500) // give it time before the last one chan.send(asyncString("END", 500)) delay(1000) // give it time to process chan.close() // close the channel ...  delay(500) // and wait some time to let it finish//sampleEnd}

{kotlin-runnable=“true” kotlin-min-compiler-version=“1.3”}

(Video) This is Why You Never Mess With a Royal Guard...

You can get the full code here.

{type=“note”}

The result of this code:

BEGINReplaceENDChannel was closed

FAQs

Is off-label prescribing legal? ›

Off-label prescribing is when a physician gives you a drug that the U.S. Food and Drug Administration (FDA) has approved to treat a condition different than your condition. This practice is legal and common. In fact, one in five prescriptions written today are for off-label use.

How do you get doctors to take you seriously? ›

Tips for Getting Your Doctor to Take You Seriously
  1. Write down your symptoms and concerns. ...
  2. Ask questions. ...
  3. Bring someone to your appointment with you. ...
  4. Don't be afraid to repeat yourself. ...
  5. Consider seeking a second opinion. ...
  6. Remember that your symptoms are real.
Jul 28, 2021

What is an example of off-label use? ›

Other off-label uses include cancer pain, hot sweats, certain psychiatric disorders, nicotine dependence, opioid withdrawal, migraine headaches, and restless leg syndrome.

What does it mean to be off-label prescribed? ›

Unapproved use of an approved drug is often called “off-label” use. This term can mean that the drug is: Used for a disease or medical condition that it is not approved to treat, such as when a chemotherapy is approved to treat one type of cancer, but healthcare providers use it to treat a different type of cancer.

Is off-label prescribing ethical? ›

ETHICS OF OFF-LABEL DRUG USE

Drugs used off-label for conditions in which little or no approved treatment indications exist in particular patient populations (such as children, pregnant women or older adults) are highly understudied. Drug safety is a concern in off-label use and continued monitoring is recommended.

What is the FDA final rule for off-label use? ›

Conclusion. Over the course of FDA's 6-year rulemaking process, the agency has made clear that knowledge of off-label use, standing alone, will not be sufficient evidence of intended use, absent circumstances showing objective intent by the firm to otherwise promote the unapproved use.

What not to say to your doctor? ›

Adam Friedman, MD: Discussing How Telemedicine can Address Disparities in Care
  • Anything that is not 100 percent truthful. ...
  • Anything condescending, loud, hostile, or sarcastic. ...
  • Anything related to your health care when we are off the clock. ...
  • Complaining about other doctors. ...
  • Anything that is a huge overreaction.
Jun 17, 2016

What is the most difficult disease to diagnose? ›

Conditions That Are Hard to Diagnose
  • Irritable Bowel Syndrome. 1/14. This condition causes pain in your belly area and changes in bathroom habits that last at least 3 months. ...
  • Celiac Disease. 2/14. ...
  • Appendicitis. 3/14. ...
  • Hyperthyroidism. 4/14. ...
  • Hypothyroidism. 5/14. ...
  • Sleep Apnea. 6/14. ...
  • Lyme Disease. 7/14. ...
  • Fibromyalgia. 8/14.
Sep 16, 2021

How common is off-label use? ›

The practice, called "off-label" prescribing, is entirely legal and very common. More than one in five outpatient prescriptions written in the U.S. are for off-label therapies. "Off-label" means the medication is being used in a manner not specified in the FDA's approved packaging label, or insert.

What is off-label medicine example? ›

Examples of off-label drug use
FDA-approved drugFDA-approved useOff-label use
modafinilimproving wakefulness in people with narcolepsy, obstructive sleep apnea, or shift work sleep disordertreating depression
escitalopramtreating depressiontreating bipolar disorder
amitriptylinetreating depressiontreating fibromyalgia
5 more rows
Jun 30, 2020

Are off-label uses FDA approved? ›

Off-label uses of a drug can become approved uses if the company that makes it obtains approval from the FDA. To gain the added approvals, the company must conduct research studies to show that the treatment is safe and effective for the new uses.

What percentage of prescribing is off-label? ›

A review of commonly used medications in general office-based practice showed that 21 percent of prescriptions were prescribed for an off-label indication.

Do prescriptions have warning labels? ›

Always read the warning labels on your prescription (if applies). The warning labels are usually on the side or back and are often separated from the main label. The package insert will describe all side-effects and warnings. Taking medication as directed by your physician can help you manage your health!

What are warnings on prescription labels? ›

Warnings. This section is typically the longest section of the Drug Facts label. It tells you about any severe side effects or drug interactions that can occur and describes who should not use the drug. It tells you when to stop using the drug and when to consult your doctor and/or pharmacist.

What are the 4 ethical principles of prescribing? ›

Respect for autonomy, beneficence, non-maleficence, and justice – referred to as the four pillars of medical ethics – are likely the first ethical principles you may have come across before or during your medical education.

Does insurance cover off-label use? ›

Coverage depends on the drug—and what condition your physician prescribes it to treat. Reimbursement for medications prescribed off-label can sometimes be difficult, as insurance companies may be wary of paying out for fraudulent reasons.

What are the 4 ethical principles in non medical prescribing? ›

Beneficence, nonmaleficence, autonomy, and justice constitute the 4 principles of ethics.

What is the difference between licensed and off-label? ›

An off-label use of a medicine is when a medicine is being used in a way that is different to that described in the product licence. Some examples of off-label uses are: using a medicine for a health condition different to that stated in the licence.

How many drugs have off-label uses? ›

Surveys have shown that approximately 1 in 5 prescriptions in the US are for off-label use. In certain populations of patients, off-label drug use is even higher.

What is the difference between on label and off-label medical device? ›

For cleared medical devices, "off-label" means any use that is not included in the cleared "indications for use." Labeling is considered any written material which accompanies, supplements, or explains the use, purpose, and indications of the product.

When your doctor is dismissive? ›

If the doctor is being dismissive, push back. Engage them as you would a partner. Let them know you appreciate their expertise, but remind them that you are the foremost expert on your own body. Work together to reach a diagnosis and treatment plan.

When a doctor dismisses your concerns? ›

Having one's symptoms dismissed by a health care professional is sometimes called “medical gaslighting,” a term that comes from Gas Light, a 1938 play that was later adapted into a movie, in which the husband manipulates his wife into questioning her perceptions of reality and her sanity.

What does it mean to be red flagged by a doctor? ›

Some of the “red flags” are: The patient is from out of state. The patient requests a specific drug. The patient states that an alternative drug does not work. The patient states that their previous physician closed their practice.

When your doctor is condescending? ›

If the doctor is condescending or makes you feel foolish, it's not a healthy partnership. Friends and family often ask me to recommend a doctor. Typically it's because for some reason they aren't happy with the current one or have developed a new medical condition and need an expert.

How do you tell if your doctor really cares about you? ›

8 Signs that Your Doctor Really Cares for You!
  • 1.Constant update. Even without you calling, good doctors must encourage multiple updates with patients. ...
  • 2.Non-tolerance. ...
  • 3.Personal talks. ...
  • 4.Transparency. ...
  • 5.Easy communication. ...
  • 6.Positive interactions. ...
  • 7.Practical suggestions. ...
  • 8.You feel satisfied.
Nov 17, 2017

What diseases do not show up in bloodwork? ›

Neurological disease such as stroke, motor neurone disease, Alzheimer's and multiple sclerosis aren't diagnosable from blood tests. Similarly, the diagnoses of depression, schizophrenia, ADHD and autism lack a specific blood diagnostic marker.

What is the hardest disease to cure? ›

Cancer. Cancer refers to the uncontrolled growth of abnormal cells in the body. This can affect almost any organ or tissue including lungs, breast, colon, skin and ovaries. Due to the complexity of the disease and the variety of forms it can take, developing a cure has proven difficult.

Which disease has no cure? ›

cancer. dementia, including Alzheimer's disease. advanced lung, heart, kidney and liver disease. stroke and other neurological diseases, including motor neurone disease and multiple sclerosis.

What is gabapentin off-label used for? ›

Gabapentin has gained widespread use since its entry to the market and a significant portion of this use has been reported as off label, including use for bipolar disorder, neuropathic pain, diabetic neuropathy, complex regional pain syndrome, attention deficit disorder, restless leg syndrome, trigeminal neuralgia, ...

What common medications are not FDA approved? ›

List of current and previously unapproved drugs
  • Colchicine. Colchicine (Colcrys, Mitigare) is used to treat and prevent gout, which is a type of painful arthritis. ...
  • Nitroglycerin. ...
  • Morphine. ...
  • Phenazopyridine. ...
  • Phenobarbital. ...
  • Potassium chloride. ...
  • Sodium fluoride.
Oct 25, 2022

What's the most serious warning on a package insert? ›

A black box warning is the FDA's most stringent warning for drugs and medical devices on the market. Black box warnings, or boxed warnings, alert the public and health care providers to serious side effects, such as injury or death.

What are off brand drugs called? ›

What are generic drugs? A generic drug is a medication with the exact same active ingredient as the brand-name drug, is taken the same way and offers the same effect. They do not need to contain the same inactive ingredients as the name-brand product and they can only be sold after the brand-name drug's patent expires.

What are off-label uses for antidepressants? ›

2. Classification of drugs for depression
Off-label useDrugsMechanism of action
Pain associated with rheumatoid arthritisParoxetineUnknown
Escitalopram
Urinary incontinenceAmitriptylineRelieve pelvic floor spasms/muscle dysfunction, increase level of serotonin
Imipramine
38 more rows
Dec 15, 2019

What are off-label drugs for OCD? ›

Citalopram (Celexa) and Escitalopram (Lexapro) are two additional selective serotonin reuptake inhibitor (SSRI) medications that are sometimes prescribed off-label to treat obsessive-compulsive disorder.

What patient populations are more commonly prescribed off-label drugs? ›

However, it is more common among patient populations that are not usually included in clinical trials, such as pregnant, pediatric, elderly, and psychiatric patients.

Can a doctor prescribe a drug that is not FDA approved? ›

Although the FDA approves all prescription drugs sold in the United States, the agency can't limit how doctors prescribe drugs after they're on the market. Doctors often direct patients to take medications for conditions that have not been approved by the FDA. This is called off-label drug use.

What is the off-label use of aspirin? ›

Used off-label for several other conditions such as preeclampsia, the emergency treatment of stroke or a heart attack, and to prevent blood clots in people with atrial fibrillation (who are unable to take anticoagulants).

What are illegal prescribing practices? ›

Prescribing large amounts of the same or similar drugs to multiple patients. Issuing multiple prescriptions to a patient with the intent to space them out over long intervals. Issuing prescriptions of drugs in unusually high doses or amounts that are not consistent with legitimate medical treatment.

Does off-label mean unlicensed? ›

Off-label' use means that the medicine has a license for treating some conditions, but that the manufacturer of the medicine has not applied for a license for it to be used to treat your condition.

Do doctors get kickbacks for prescribing certain drugs? ›

Ornstein continued, "It's illegal to give kickbacks to a doctor to prescribe drugs, but it is legal to give money to doctors to help promote your drug. Some doctors make tens of thousands or hundreds of thousands of dollars a year beyond their normal practice just for working with the industry."

What are the 6 rights of prescribing? ›

something known as the '6 R's', which stands for right resident, right medicine, right route, right dose, right time, resident's right to refuse. what to do if the person is having a meal or is asleep. using the right equipment to give the medicine.

What is an example of inappropriate prescribing? ›

Underprescribing: This is failing to prescribe a beneficial or clinically indicated medication. For example, an HCP does not prescribe an ACE inhibitor for renal protection to a person with diabetes.

What percentage of drugs are prescribed off-label? ›

A review of commonly used medications in general office-based practice showed that 21 percent of prescriptions were prescribed for an off-label indication.

Why do doctors prescribe off-label? ›

Off-label prescribing is a common and legal practice in medicine. This practice is justified when scientific evidence suggests the efficacy and safety of a medication for an indication for which it does not have FDA approval and when the practice is supported by expert consensus or practice guidelines.

What is an example of off-label use of medicine? ›

TABLE
Category and drugOff-label use(s)a
IsofluraneSeizure, status epilepticus
DonepezilFrontotemporal dementia23
GabapentinBipolar disorder, diabetes, fibromyalgia, neuropathic pain symptoms, headache, hiccups, hot flashes, restless leg syndrome24
LidocainePostherpetic neuralgia24
53 more rows

What does NICE approved mean? ›

NICE makes decisions on whether a drug or treatment should be available based on: evidence - NICE reviews each treatment or new technique and bases their decision on the best available evidence.

Does Medicare pay for off-label? ›

Drugs used for indications other than those in the approved labeling may be covered under Medicare if it is determined that the use is medically accepted, taking into consideration the major drug compendia, authoritative medical literatures and/or accepted standards of medical practice.

Does insurance cover non FDA approved treatments? ›

If the drug is not a medication approved for sale and use in the U.S. in humans by the FDA then coverage will not be provided. 5.

Videos

1. When Did You Start Preparing For IAS Exam?- Shruti Sharma, AIR-1, CSE 2021 #shorts
(ForumIAS Official)
2. Top 10 Celebrities Who Destroyed Their Careers On Late Night Shows
(Top 10 Beyond The Screen)
3. School Regrets Trans Pronoun Rule After Christian Dad Tells His Pronouns
(Facts World)
4. Create Organization Chart in 2 Minutes | Power Point Tutorials
(Learn for Future)
5. Maths Super Tricks - Dear Sir - #shorts #maths #shorttrick #mathstricks #examtrick
(Dear Sir)
6. Learn Regular Expressions In 20 Minutes
(Web Dev Simplified)
Top Articles
Latest Posts
Article information

Author: Sen. Emmett Berge

Last Updated: 21/03/2023

Views: 5789

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Sen. Emmett Berge

Birthday: 1993-06-17

Address: 787 Elvis Divide, Port Brice, OH 24507-6802

Phone: +9779049645255

Job: Senior Healthcare Specialist

Hobby: Cycling, Model building, Kitesurfing, Origami, Lapidary, Dance, Basketball

Introduction: My name is Sen. Emmett Berge, I am a funny, vast, charming, courageous, enthusiastic, jolly, famous person who loves writing and wants to share my knowledge and understanding with you.