I am new to kotlin , so need help to understand the code ,I went to a blogs and found something like this and implemented in my code , code work perfect but i can't understand the following things .
Basically , I got lost in how lazyDefferd function , how it's works internally.
a. How generic T is passed .
b. What it mean by this CoroutineScope.()
as i know this is input that i need to pass from the ViewModel
but how it's getting pass i can't understand .
interface MovieRepository {
suspend fun getTopRatedMovie(page:Int): LiveData<out List<TopRatedMovieEntity>>
}
ViewModel :
class TopRatedMovieViewModel(movieRepository: MovieRepository):ViewModel() {
val topMovie by lazyDefferd{
movieRepository.getTopRatedMovie(1)
}
}
fun <T> lazyDefferd(block:suspend CoroutineScope.()->T):Lazy<Deferred<T>>{
return lazy {
GlobalScope.async(start = CoroutineStart.LAZY) {
block.invoke(this)
}
}
}
a. How generic T is passed.
You can pass it explicitly, e.g.:
val myLazyDeffered = lazyDefferd<SomeType> {
// …
}
But the compiler can usually infer the type, so it's more usual to omit it (unless there's a reason why it's not clear from the code). That's what's happening in your topMovie
example: the compiler knows what type the lambda returns, so it infers T
from that.
(As you've probably already noted, lazyDefferd()
also takes a value parameter, but since it's the last parameter and a lambda, Kotlin lets you omit the parens.)
b. What it mean by this
CoroutineScope.()
That's a function literal with receiver. The lambda that you pass to block
will behave as if it's an extension method on the CoroutineScope
class: inside the lambda, this
will refer to a CoroutineScope
instance. It's similar to passing the instance as a parameter to the lambda (and in this case, that's how it's called), but the syntax is more concise.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments