Created
September 4, 2019 15:09
-
-
Save mitchtabian/f7e152b0ca2881e5238a96f8177f7eca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
System.out: DEBUG: ApiService: 98713473 // on App start | |
System.out: DEBUG: ApiService: 98713473 // Rotate | |
System.out: DEBUG: ApiService: 98713473 // Rotate |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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