How can I use coroutines with volley so that my code can be written like sychronous?












1















Here's an example from developer.android.com



class MainActivity : AppCompatActivity() {

lateinit var textView:TextView
lateinit var button:Button

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

textView = findViewById(R.id.textView)
button = findViewById(R.id.button)

button.setOnClickListener({
getData()
})
}

fun getData(){
val queue = Volley.newRequestQueue(this)
val url = "http://www.google.com/"

val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
textView.text = "Response is: ${response.substring(0, 500)}"
},
Response.ErrorListener { textView.text = "Something went wrong!" })

queue.add(stringRequest)
}
}


How can I take advantage of coroutines so I can write my code in this manner:



val data = getData()
textView.text = data









share|improve this question





























    1















    Here's an example from developer.android.com



    class MainActivity : AppCompatActivity() {

    lateinit var textView:TextView
    lateinit var button:Button

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    textView = findViewById(R.id.textView)
    button = findViewById(R.id.button)

    button.setOnClickListener({
    getData()
    })
    }

    fun getData(){
    val queue = Volley.newRequestQueue(this)
    val url = "http://www.google.com/"

    val stringRequest = StringRequest(Request.Method.GET, url,
    Response.Listener<String> { response ->
    textView.text = "Response is: ${response.substring(0, 500)}"
    },
    Response.ErrorListener { textView.text = "Something went wrong!" })

    queue.add(stringRequest)
    }
    }


    How can I take advantage of coroutines so I can write my code in this manner:



    val data = getData()
    textView.text = data









    share|improve this question



























      1












      1








      1








      Here's an example from developer.android.com



      class MainActivity : AppCompatActivity() {

      lateinit var textView:TextView
      lateinit var button:Button

      override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)

      textView = findViewById(R.id.textView)
      button = findViewById(R.id.button)

      button.setOnClickListener({
      getData()
      })
      }

      fun getData(){
      val queue = Volley.newRequestQueue(this)
      val url = "http://www.google.com/"

      val stringRequest = StringRequest(Request.Method.GET, url,
      Response.Listener<String> { response ->
      textView.text = "Response is: ${response.substring(0, 500)}"
      },
      Response.ErrorListener { textView.text = "Something went wrong!" })

      queue.add(stringRequest)
      }
      }


      How can I take advantage of coroutines so I can write my code in this manner:



      val data = getData()
      textView.text = data









      share|improve this question
















      Here's an example from developer.android.com



      class MainActivity : AppCompatActivity() {

      lateinit var textView:TextView
      lateinit var button:Button

      override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)

      textView = findViewById(R.id.textView)
      button = findViewById(R.id.button)

      button.setOnClickListener({
      getData()
      })
      }

      fun getData(){
      val queue = Volley.newRequestQueue(this)
      val url = "http://www.google.com/"

      val stringRequest = StringRequest(Request.Method.GET, url,
      Response.Listener<String> { response ->
      textView.text = "Response is: ${response.substring(0, 500)}"
      },
      Response.ErrorListener { textView.text = "Something went wrong!" })

      queue.add(stringRequest)
      }
      }


      How can I take advantage of coroutines so I can write my code in this manner:



      val data = getData()
      textView.text = data






      kotlin android-volley coroutine






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 26 '18 at 18:04







      Lance

















      asked Nov 26 '18 at 17:19









      LanceLance

      1,23822042




      1,23822042
























          1 Answer
          1






          active

          oldest

          votes


















          3














          You can use suspendCoroutine, see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/suspend-coroutine.html



          suspend fun getData() = suspendCoroutine<String> { cont ->
          val queue = Volley.newRequestQueue(this)
          val url = "http://www.google.com/"

          val stringRequest = StringRequest(Request.Method.GET, url,
          Response.Listener<String> { response ->
          cont.resume("Response is: ${response.substring(0, 500)}")
          },
          Response.ErrorListener { cont.resume("Something went wrong!") })

          queue.add(stringRequest)
          }


          You should implement your activity like described here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy



          class MainActivity: AppCompatActivity(), CoroutineScope {
          protected lateinit var job: Job
          override val coroutineContext: CoroutineContext
          get() = job + Dispatchers.Main

          override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          job = Job()
          ...
          button.setOnClickListener({
          launch {
          val data = getData()
          textView.text = data
          }
          })
          }

          override fun onDestroy() {
          super.onDestroy()
          job.cancel()
          }
          }





          share|improve this answer


























          • how can I use that in the context of updating the textView.text? Let's say in the onclick listener in my example above, how will I be able to use this suspend function to get the data and update the textview?

            – Lance
            Nov 26 '18 at 19:41













          • Extended my answer with an application of the getData() function

            – Rene
            Nov 26 '18 at 20:12











          • That worked, thanks Rene. Does that mean that I have to implement coroutinescope in every activity that I'm going to use coroutine with?

            – Lance
            Nov 26 '18 at 20:27






          • 1





            Yes you have. That is the reason, why a base class (see link) is useful.

            – Rene
            Nov 26 '18 at 20:34











          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%2f53486087%2fhow-can-i-use-coroutines-with-volley-so-that-my-code-can-be-written-like-sychron%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          You can use suspendCoroutine, see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/suspend-coroutine.html



          suspend fun getData() = suspendCoroutine<String> { cont ->
          val queue = Volley.newRequestQueue(this)
          val url = "http://www.google.com/"

          val stringRequest = StringRequest(Request.Method.GET, url,
          Response.Listener<String> { response ->
          cont.resume("Response is: ${response.substring(0, 500)}")
          },
          Response.ErrorListener { cont.resume("Something went wrong!") })

          queue.add(stringRequest)
          }


          You should implement your activity like described here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy



          class MainActivity: AppCompatActivity(), CoroutineScope {
          protected lateinit var job: Job
          override val coroutineContext: CoroutineContext
          get() = job + Dispatchers.Main

          override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          job = Job()
          ...
          button.setOnClickListener({
          launch {
          val data = getData()
          textView.text = data
          }
          })
          }

          override fun onDestroy() {
          super.onDestroy()
          job.cancel()
          }
          }





          share|improve this answer


























          • how can I use that in the context of updating the textView.text? Let's say in the onclick listener in my example above, how will I be able to use this suspend function to get the data and update the textview?

            – Lance
            Nov 26 '18 at 19:41













          • Extended my answer with an application of the getData() function

            – Rene
            Nov 26 '18 at 20:12











          • That worked, thanks Rene. Does that mean that I have to implement coroutinescope in every activity that I'm going to use coroutine with?

            – Lance
            Nov 26 '18 at 20:27






          • 1





            Yes you have. That is the reason, why a base class (see link) is useful.

            – Rene
            Nov 26 '18 at 20:34
















          3














          You can use suspendCoroutine, see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/suspend-coroutine.html



          suspend fun getData() = suspendCoroutine<String> { cont ->
          val queue = Volley.newRequestQueue(this)
          val url = "http://www.google.com/"

          val stringRequest = StringRequest(Request.Method.GET, url,
          Response.Listener<String> { response ->
          cont.resume("Response is: ${response.substring(0, 500)}")
          },
          Response.ErrorListener { cont.resume("Something went wrong!") })

          queue.add(stringRequest)
          }


          You should implement your activity like described here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy



          class MainActivity: AppCompatActivity(), CoroutineScope {
          protected lateinit var job: Job
          override val coroutineContext: CoroutineContext
          get() = job + Dispatchers.Main

          override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          job = Job()
          ...
          button.setOnClickListener({
          launch {
          val data = getData()
          textView.text = data
          }
          })
          }

          override fun onDestroy() {
          super.onDestroy()
          job.cancel()
          }
          }





          share|improve this answer


























          • how can I use that in the context of updating the textView.text? Let's say in the onclick listener in my example above, how will I be able to use this suspend function to get the data and update the textview?

            – Lance
            Nov 26 '18 at 19:41













          • Extended my answer with an application of the getData() function

            – Rene
            Nov 26 '18 at 20:12











          • That worked, thanks Rene. Does that mean that I have to implement coroutinescope in every activity that I'm going to use coroutine with?

            – Lance
            Nov 26 '18 at 20:27






          • 1





            Yes you have. That is the reason, why a base class (see link) is useful.

            – Rene
            Nov 26 '18 at 20:34














          3












          3








          3







          You can use suspendCoroutine, see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/suspend-coroutine.html



          suspend fun getData() = suspendCoroutine<String> { cont ->
          val queue = Volley.newRequestQueue(this)
          val url = "http://www.google.com/"

          val stringRequest = StringRequest(Request.Method.GET, url,
          Response.Listener<String> { response ->
          cont.resume("Response is: ${response.substring(0, 500)}")
          },
          Response.ErrorListener { cont.resume("Something went wrong!") })

          queue.add(stringRequest)
          }


          You should implement your activity like described here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy



          class MainActivity: AppCompatActivity(), CoroutineScope {
          protected lateinit var job: Job
          override val coroutineContext: CoroutineContext
          get() = job + Dispatchers.Main

          override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          job = Job()
          ...
          button.setOnClickListener({
          launch {
          val data = getData()
          textView.text = data
          }
          })
          }

          override fun onDestroy() {
          super.onDestroy()
          job.cancel()
          }
          }





          share|improve this answer















          You can use suspendCoroutine, see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/suspend-coroutine.html



          suspend fun getData() = suspendCoroutine<String> { cont ->
          val queue = Volley.newRequestQueue(this)
          val url = "http://www.google.com/"

          val stringRequest = StringRequest(Request.Method.GET, url,
          Response.Listener<String> { response ->
          cont.resume("Response is: ${response.substring(0, 500)}")
          },
          Response.ErrorListener { cont.resume("Something went wrong!") })

          queue.add(stringRequest)
          }


          You should implement your activity like described here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy



          class MainActivity: AppCompatActivity(), CoroutineScope {
          protected lateinit var job: Job
          override val coroutineContext: CoroutineContext
          get() = job + Dispatchers.Main

          override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          job = Job()
          ...
          button.setOnClickListener({
          launch {
          val data = getData()
          textView.text = data
          }
          })
          }

          override fun onDestroy() {
          super.onDestroy()
          job.cancel()
          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 26 '18 at 20:11

























          answered Nov 26 '18 at 17:29









          ReneRene

          2,07627




          2,07627













          • how can I use that in the context of updating the textView.text? Let's say in the onclick listener in my example above, how will I be able to use this suspend function to get the data and update the textview?

            – Lance
            Nov 26 '18 at 19:41













          • Extended my answer with an application of the getData() function

            – Rene
            Nov 26 '18 at 20:12











          • That worked, thanks Rene. Does that mean that I have to implement coroutinescope in every activity that I'm going to use coroutine with?

            – Lance
            Nov 26 '18 at 20:27






          • 1





            Yes you have. That is the reason, why a base class (see link) is useful.

            – Rene
            Nov 26 '18 at 20:34



















          • how can I use that in the context of updating the textView.text? Let's say in the onclick listener in my example above, how will I be able to use this suspend function to get the data and update the textview?

            – Lance
            Nov 26 '18 at 19:41













          • Extended my answer with an application of the getData() function

            – Rene
            Nov 26 '18 at 20:12











          • That worked, thanks Rene. Does that mean that I have to implement coroutinescope in every activity that I'm going to use coroutine with?

            – Lance
            Nov 26 '18 at 20:27






          • 1





            Yes you have. That is the reason, why a base class (see link) is useful.

            – Rene
            Nov 26 '18 at 20:34

















          how can I use that in the context of updating the textView.text? Let's say in the onclick listener in my example above, how will I be able to use this suspend function to get the data and update the textview?

          – Lance
          Nov 26 '18 at 19:41







          how can I use that in the context of updating the textView.text? Let's say in the onclick listener in my example above, how will I be able to use this suspend function to get the data and update the textview?

          – Lance
          Nov 26 '18 at 19:41















          Extended my answer with an application of the getData() function

          – Rene
          Nov 26 '18 at 20:12





          Extended my answer with an application of the getData() function

          – Rene
          Nov 26 '18 at 20:12













          That worked, thanks Rene. Does that mean that I have to implement coroutinescope in every activity that I'm going to use coroutine with?

          – Lance
          Nov 26 '18 at 20:27





          That worked, thanks Rene. Does that mean that I have to implement coroutinescope in every activity that I'm going to use coroutine with?

          – Lance
          Nov 26 '18 at 20:27




          1




          1





          Yes you have. That is the reason, why a base class (see link) is useful.

          – Rene
          Nov 26 '18 at 20:34





          Yes you have. That is the reason, why a base class (see link) is useful.

          – Rene
          Nov 26 '18 at 20:34




















          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%2f53486087%2fhow-can-i-use-coroutines-with-volley-so-that-my-code-can-be-written-like-sychron%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

          Contact image not getting when fetch all contact list from iPhone by CNContact

          count number of partitions of a set with n elements into k subsets

          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks