Skip to content

Instantly share code, notes, and snippets.

@mitchtabian mitchtabian/Log.txt
Created Sep 4, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.