Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Created September 4, 2019 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchtabian/f7e152b0ca2881e5238a96f8177f7eca to your computer and use it in GitHub Desktop.
Save mitchtabian/f7e152b0ca2881e5238a96f8177f7eca to your computer and use it in GitHub Desktop.
System.out: DEBUG: ApiService: 98713473 // on App start
System.out: DEBUG: ApiService: 98713473 // Rotate
System.out: DEBUG: ApiService: 98713473 // Rotate
class MainActivity : AppCompatActivity() {
lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
viewModel.user.observe(this, Observer { user ->
println("DEBUG: ${user}")
})
viewModel.setUserId("1")
}
override fun onDestroy() {
super.onDestroy()
viewModel.cancelJobs()
viewModel.setUserId("2")
}
}
object Repository {
var job: CompletableJob? = null
fun getUser(userId: String): LiveData<User>{
job = Job()
return object: LiveData<User>(){
override fun onActive() {
super.onActive()
job?.let{ theJob ->
CoroutineScope(IO + theJob).launch {
val apiService = MyRetrofitBuilder.apiService
println("DEBUG: ApiService: ${apiService.hashCode()}")
val user = apiService.getUser(userId)
withContext(Main){
value = user
theJob.complete()
}
}
}
}
}
}
fun cancelJobs(){
job?.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment