Difference between Job and Deferred in Coroutines Kotlin












6















I am new to coroutines, I understand launch and async but still confusing part is deferred. What is deferred? and different between job and deferred.Clear explanation and Example is more helpful. Thanks in advance










share|improve this question





























    6















    I am new to coroutines, I understand launch and async but still confusing part is deferred. What is deferred? and different between job and deferred.Clear explanation and Example is more helpful. Thanks in advance










    share|improve this question



























      6












      6








      6


      1






      I am new to coroutines, I understand launch and async but still confusing part is deferred. What is deferred? and different between job and deferred.Clear explanation and Example is more helpful. Thanks in advance










      share|improve this question
















      I am new to coroutines, I understand launch and async but still confusing part is deferred. What is deferred? and different between job and deferred.Clear explanation and Example is more helpful. Thanks in advance







      android kotlin deferred kotlinx.coroutines






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 12:27









      Abdul Rehman

      1,1661325




      1,1661325










      asked Nov 22 '18 at 9:52









      Magesh PandianMagesh Pandian

      2,13621231




      2,13621231
























          2 Answers
          2






          active

          oldest

          votes


















          4














          So job is sort of an object that represents a coroutine's execution and is related to structured concurrency, e.g. you can cancel a job, and all the children of this job will be also cancelled.



          From docs:




          Job is a cancellable thing with a life-cycle that culminates in its completion.




          Deferred is some kind of analog of Future in Java: in encapsulates an operation that will be finished at some point in future after it's initialization. But is also related to coroutines in Kotlin.



          From documentation:




          Deferred value is a non-blocking cancellable future — it is a Job that has a result.




          So, Deferred is a Job that has a result:




          A deferred value is a Job. A job in the coroutineContext of async builder represents the coroutine itself.




          An example:



          someScope.launch {
          val userJob: Deferred<User> = async(IO) { repository.getUser(id) }
          //some operations, while user is being retrieved
          val user = userJob.await() //here coroutine will be suspended for a while, and the method `await` is available only from `Deferred` interface
          //do the job with retrieved user
          }


          Also, it is possible to structure this async request with an existing scope, but that is a talk of another question.






          share|improve this answer


























          • Thanks llyunin, can explain with piece of code-snipets more helpful

            – Magesh Pandian
            Nov 22 '18 at 10:27











          • @MageshPandian, I've edited the answer. Also, Deferred interface is also extended with some another convenient methods, but they are for now marked as experimental (Kotlin 1.3)

            – Andrey Ilyunin
            Nov 22 '18 at 10:34











          • I think it's worth pointing out differences in exception handling which might be significant in some use cases; launch is throwing immediately while async throws exceptions as a "result" when calling await().

            – Pawel
            Nov 22 '18 at 13:00











          • @Pawel There's yet another important point: async also immediately cancels its parent job, which then propagates cancellation to all other async tasks. This happens whether or not you await on it. You can prevent this by using SupervisorJob as a parent, but that would be abuse of the mechanism.

            – Marko Topolnik
            Nov 23 '18 at 9:22





















          2














          On a basic level, Deferred is a future. It makes it possible for one coroutine to wait for the result produced by another one, suspending itself until it's ready. Calling async is one way, but by far not the only way, to get a Deferred.



          However, I think your question is more about the basics: when to use launch, when to use async-await. Here's an important lesson: you probably don't need async. People tend to use it because the keywords async and await are familiar from other languages, but in Kotlin, async is not a general-purpose tool to achieve non-blocking calls.



          Here's a basic recipe on how to turn a blocking call into a suspending, non-blocking one:



          uiScope.launch {
          val ioResult = withContext(Dispatchers.IO) { blockingIOCall() }
          ... just use the result, you're on the GUI thread here.
          }





          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428179%2fdifference-between-job-and-deferred-in-coroutines-kotlin%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4














            So job is sort of an object that represents a coroutine's execution and is related to structured concurrency, e.g. you can cancel a job, and all the children of this job will be also cancelled.



            From docs:




            Job is a cancellable thing with a life-cycle that culminates in its completion.




            Deferred is some kind of analog of Future in Java: in encapsulates an operation that will be finished at some point in future after it's initialization. But is also related to coroutines in Kotlin.



            From documentation:




            Deferred value is a non-blocking cancellable future — it is a Job that has a result.




            So, Deferred is a Job that has a result:




            A deferred value is a Job. A job in the coroutineContext of async builder represents the coroutine itself.




            An example:



            someScope.launch {
            val userJob: Deferred<User> = async(IO) { repository.getUser(id) }
            //some operations, while user is being retrieved
            val user = userJob.await() //here coroutine will be suspended for a while, and the method `await` is available only from `Deferred` interface
            //do the job with retrieved user
            }


            Also, it is possible to structure this async request with an existing scope, but that is a talk of another question.






            share|improve this answer


























            • Thanks llyunin, can explain with piece of code-snipets more helpful

              – Magesh Pandian
              Nov 22 '18 at 10:27











            • @MageshPandian, I've edited the answer. Also, Deferred interface is also extended with some another convenient methods, but they are for now marked as experimental (Kotlin 1.3)

              – Andrey Ilyunin
              Nov 22 '18 at 10:34











            • I think it's worth pointing out differences in exception handling which might be significant in some use cases; launch is throwing immediately while async throws exceptions as a "result" when calling await().

              – Pawel
              Nov 22 '18 at 13:00











            • @Pawel There's yet another important point: async also immediately cancels its parent job, which then propagates cancellation to all other async tasks. This happens whether or not you await on it. You can prevent this by using SupervisorJob as a parent, but that would be abuse of the mechanism.

              – Marko Topolnik
              Nov 23 '18 at 9:22


















            4














            So job is sort of an object that represents a coroutine's execution and is related to structured concurrency, e.g. you can cancel a job, and all the children of this job will be also cancelled.



            From docs:




            Job is a cancellable thing with a life-cycle that culminates in its completion.




            Deferred is some kind of analog of Future in Java: in encapsulates an operation that will be finished at some point in future after it's initialization. But is also related to coroutines in Kotlin.



            From documentation:




            Deferred value is a non-blocking cancellable future — it is a Job that has a result.




            So, Deferred is a Job that has a result:




            A deferred value is a Job. A job in the coroutineContext of async builder represents the coroutine itself.




            An example:



            someScope.launch {
            val userJob: Deferred<User> = async(IO) { repository.getUser(id) }
            //some operations, while user is being retrieved
            val user = userJob.await() //here coroutine will be suspended for a while, and the method `await` is available only from `Deferred` interface
            //do the job with retrieved user
            }


            Also, it is possible to structure this async request with an existing scope, but that is a talk of another question.






            share|improve this answer


























            • Thanks llyunin, can explain with piece of code-snipets more helpful

              – Magesh Pandian
              Nov 22 '18 at 10:27











            • @MageshPandian, I've edited the answer. Also, Deferred interface is also extended with some another convenient methods, but they are for now marked as experimental (Kotlin 1.3)

              – Andrey Ilyunin
              Nov 22 '18 at 10:34











            • I think it's worth pointing out differences in exception handling which might be significant in some use cases; launch is throwing immediately while async throws exceptions as a "result" when calling await().

              – Pawel
              Nov 22 '18 at 13:00











            • @Pawel There's yet another important point: async also immediately cancels its parent job, which then propagates cancellation to all other async tasks. This happens whether or not you await on it. You can prevent this by using SupervisorJob as a parent, but that would be abuse of the mechanism.

              – Marko Topolnik
              Nov 23 '18 at 9:22
















            4












            4








            4







            So job is sort of an object that represents a coroutine's execution and is related to structured concurrency, e.g. you can cancel a job, and all the children of this job will be also cancelled.



            From docs:




            Job is a cancellable thing with a life-cycle that culminates in its completion.




            Deferred is some kind of analog of Future in Java: in encapsulates an operation that will be finished at some point in future after it's initialization. But is also related to coroutines in Kotlin.



            From documentation:




            Deferred value is a non-blocking cancellable future — it is a Job that has a result.




            So, Deferred is a Job that has a result:




            A deferred value is a Job. A job in the coroutineContext of async builder represents the coroutine itself.




            An example:



            someScope.launch {
            val userJob: Deferred<User> = async(IO) { repository.getUser(id) }
            //some operations, while user is being retrieved
            val user = userJob.await() //here coroutine will be suspended for a while, and the method `await` is available only from `Deferred` interface
            //do the job with retrieved user
            }


            Also, it is possible to structure this async request with an existing scope, but that is a talk of another question.






            share|improve this answer















            So job is sort of an object that represents a coroutine's execution and is related to structured concurrency, e.g. you can cancel a job, and all the children of this job will be also cancelled.



            From docs:




            Job is a cancellable thing with a life-cycle that culminates in its completion.




            Deferred is some kind of analog of Future in Java: in encapsulates an operation that will be finished at some point in future after it's initialization. But is also related to coroutines in Kotlin.



            From documentation:




            Deferred value is a non-blocking cancellable future — it is a Job that has a result.




            So, Deferred is a Job that has a result:




            A deferred value is a Job. A job in the coroutineContext of async builder represents the coroutine itself.




            An example:



            someScope.launch {
            val userJob: Deferred<User> = async(IO) { repository.getUser(id) }
            //some operations, while user is being retrieved
            val user = userJob.await() //here coroutine will be suspended for a while, and the method `await` is available only from `Deferred` interface
            //do the job with retrieved user
            }


            Also, it is possible to structure this async request with an existing scope, but that is a talk of another question.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 22 '18 at 10:29

























            answered Nov 22 '18 at 10:16









            Andrey IlyuninAndrey Ilyunin

            1,318220




            1,318220













            • Thanks llyunin, can explain with piece of code-snipets more helpful

              – Magesh Pandian
              Nov 22 '18 at 10:27











            • @MageshPandian, I've edited the answer. Also, Deferred interface is also extended with some another convenient methods, but they are for now marked as experimental (Kotlin 1.3)

              – Andrey Ilyunin
              Nov 22 '18 at 10:34











            • I think it's worth pointing out differences in exception handling which might be significant in some use cases; launch is throwing immediately while async throws exceptions as a "result" when calling await().

              – Pawel
              Nov 22 '18 at 13:00











            • @Pawel There's yet another important point: async also immediately cancels its parent job, which then propagates cancellation to all other async tasks. This happens whether or not you await on it. You can prevent this by using SupervisorJob as a parent, but that would be abuse of the mechanism.

              – Marko Topolnik
              Nov 23 '18 at 9:22





















            • Thanks llyunin, can explain with piece of code-snipets more helpful

              – Magesh Pandian
              Nov 22 '18 at 10:27











            • @MageshPandian, I've edited the answer. Also, Deferred interface is also extended with some another convenient methods, but they are for now marked as experimental (Kotlin 1.3)

              – Andrey Ilyunin
              Nov 22 '18 at 10:34











            • I think it's worth pointing out differences in exception handling which might be significant in some use cases; launch is throwing immediately while async throws exceptions as a "result" when calling await().

              – Pawel
              Nov 22 '18 at 13:00











            • @Pawel There's yet another important point: async also immediately cancels its parent job, which then propagates cancellation to all other async tasks. This happens whether or not you await on it. You can prevent this by using SupervisorJob as a parent, but that would be abuse of the mechanism.

              – Marko Topolnik
              Nov 23 '18 at 9:22



















            Thanks llyunin, can explain with piece of code-snipets more helpful

            – Magesh Pandian
            Nov 22 '18 at 10:27





            Thanks llyunin, can explain with piece of code-snipets more helpful

            – Magesh Pandian
            Nov 22 '18 at 10:27













            @MageshPandian, I've edited the answer. Also, Deferred interface is also extended with some another convenient methods, but they are for now marked as experimental (Kotlin 1.3)

            – Andrey Ilyunin
            Nov 22 '18 at 10:34





            @MageshPandian, I've edited the answer. Also, Deferred interface is also extended with some another convenient methods, but they are for now marked as experimental (Kotlin 1.3)

            – Andrey Ilyunin
            Nov 22 '18 at 10:34













            I think it's worth pointing out differences in exception handling which might be significant in some use cases; launch is throwing immediately while async throws exceptions as a "result" when calling await().

            – Pawel
            Nov 22 '18 at 13:00





            I think it's worth pointing out differences in exception handling which might be significant in some use cases; launch is throwing immediately while async throws exceptions as a "result" when calling await().

            – Pawel
            Nov 22 '18 at 13:00













            @Pawel There's yet another important point: async also immediately cancels its parent job, which then propagates cancellation to all other async tasks. This happens whether or not you await on it. You can prevent this by using SupervisorJob as a parent, but that would be abuse of the mechanism.

            – Marko Topolnik
            Nov 23 '18 at 9:22







            @Pawel There's yet another important point: async also immediately cancels its parent job, which then propagates cancellation to all other async tasks. This happens whether or not you await on it. You can prevent this by using SupervisorJob as a parent, but that would be abuse of the mechanism.

            – Marko Topolnik
            Nov 23 '18 at 9:22















            2














            On a basic level, Deferred is a future. It makes it possible for one coroutine to wait for the result produced by another one, suspending itself until it's ready. Calling async is one way, but by far not the only way, to get a Deferred.



            However, I think your question is more about the basics: when to use launch, when to use async-await. Here's an important lesson: you probably don't need async. People tend to use it because the keywords async and await are familiar from other languages, but in Kotlin, async is not a general-purpose tool to achieve non-blocking calls.



            Here's a basic recipe on how to turn a blocking call into a suspending, non-blocking one:



            uiScope.launch {
            val ioResult = withContext(Dispatchers.IO) { blockingIOCall() }
            ... just use the result, you're on the GUI thread here.
            }





            share|improve this answer






























              2














              On a basic level, Deferred is a future. It makes it possible for one coroutine to wait for the result produced by another one, suspending itself until it's ready. Calling async is one way, but by far not the only way, to get a Deferred.



              However, I think your question is more about the basics: when to use launch, when to use async-await. Here's an important lesson: you probably don't need async. People tend to use it because the keywords async and await are familiar from other languages, but in Kotlin, async is not a general-purpose tool to achieve non-blocking calls.



              Here's a basic recipe on how to turn a blocking call into a suspending, non-blocking one:



              uiScope.launch {
              val ioResult = withContext(Dispatchers.IO) { blockingIOCall() }
              ... just use the result, you're on the GUI thread here.
              }





              share|improve this answer




























                2












                2








                2







                On a basic level, Deferred is a future. It makes it possible for one coroutine to wait for the result produced by another one, suspending itself until it's ready. Calling async is one way, but by far not the only way, to get a Deferred.



                However, I think your question is more about the basics: when to use launch, when to use async-await. Here's an important lesson: you probably don't need async. People tend to use it because the keywords async and await are familiar from other languages, but in Kotlin, async is not a general-purpose tool to achieve non-blocking calls.



                Here's a basic recipe on how to turn a blocking call into a suspending, non-blocking one:



                uiScope.launch {
                val ioResult = withContext(Dispatchers.IO) { blockingIOCall() }
                ... just use the result, you're on the GUI thread here.
                }





                share|improve this answer















                On a basic level, Deferred is a future. It makes it possible for one coroutine to wait for the result produced by another one, suspending itself until it's ready. Calling async is one way, but by far not the only way, to get a Deferred.



                However, I think your question is more about the basics: when to use launch, when to use async-await. Here's an important lesson: you probably don't need async. People tend to use it because the keywords async and await are familiar from other languages, but in Kotlin, async is not a general-purpose tool to achieve non-blocking calls.



                Here's a basic recipe on how to turn a blocking call into a suspending, non-blocking one:



                uiScope.launch {
                val ioResult = withContext(Dispatchers.IO) { blockingIOCall() }
                ... just use the result, you're on the GUI thread here.
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 22 '18 at 12:06

























                answered Nov 22 '18 at 11:46









                Marko TopolnikMarko Topolnik

                147k19198326




                147k19198326






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428179%2fdifference-between-job-and-deferred-in-coroutines-kotlin%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                    How to fix TextFormField cause rebuild widget in Flutter