https://kotlinlang.org logo
#android
Title
# android
d

dr.henry

11/15/2017, 6:33 PM
What would be the kotlin version of this? Runnable r = new Runnable() { @Override public void run() { while (mStatus) { synchronized (this) { try { wait(1000 * 60); } catch (Exception e) { e.printStackTrace(); continue; } } sendRequest(); } } }; thread = new Thread(r); thread.start();
i

Itua

11/15/2017, 6:36 PM
I think you can copy and paste that in the IDE and it will convert it for you into Kotlin
d

dr.henry

11/15/2017, 6:39 PM
when I use convert, "wait" is not usable
continue is not usable
j

James

11/15/2017, 6:47 PM
Copy code
thread(start = true) {
      while(mStatus) {
        synchronized(this) {
          Thread.sleep(60_000)
          sendRequest()
        }
      }
    }
Allow the interrupt exception to propagate up?
d

dr.henry

11/15/2017, 6:54 PM
It cause hang app
j

James

11/15/2017, 6:59 PM
If you really need to call
wait
you can cast to java.lang.Object.
You can also return a value from
synchronised
Copy code
while(mStatus) {
  val shouldSendRequest = synchronized(this) {
    try {
      (this as java.lang.Object).wait(60_000)
      true
    } catch (ex: Exception) {
      false
    }
  }

  if (shouldSendRequest) sendRequest()
}
d

dr.henry

11/15/2017, 7:15 PM
I will test it and say the result
o

oianmol

11/16/2017, 5:59 AM
you can also use coroutines , i assume
d

dr.henry

11/16/2017, 10:22 AM
@James The whole problem was from my code. I was using "thread.run()" for run created Thread. Thanks a lot
@oianmol Isn't coroutines hard to learn? and isn't it is experimental stage?
o

oianmol

11/16/2017, 10:25 AM
@dr.henry its easy very easy , also experimental is temporary , If you dont want to use coroutines then you can use RxJAVA it has a lot of operators for the use case.
d

dr.henry

11/16/2017, 10:26 AM
Do you can give me a good reference to learn coroutines?
d

dave08

11/16/2017, 10:33 AM
Try the kotlinx.coroutines repo, we're using it, and it's much less mess than threads and runners, and we're also switching from rx....
d

dr.henry

11/16/2017, 10:35 AM
Thanks a lot
5 Views