Browse Source
Add some ProfileFragmentViewModel logic and tests
renovate/org.robolectric-robolectric-4.x
Add some ProfileFragmentViewModel logic and tests
renovate/org.robolectric-robolectric-4.x
Ammar Githam
4 years ago
5 changed files with 122 additions and 17 deletions
-
3app/build.gradle
-
2app/src/main/java/awais/instagrabber/fragments/main/ProfileFragment.java
-
46app/src/main/java/awais/instagrabber/viewmodels/ProfileFragmentViewModel.kt
-
41app/src/test/java/awais/instagrabber/LiveDataTestUtil.kt
-
47app/src/test/java/awais/instagrabber/viewmodels/ProfileFragmentViewModelTest.kt
@ -0,0 +1,41 @@ |
|||
package awais.instagrabber |
|||
|
|||
import androidx.annotation.VisibleForTesting |
|||
import androidx.lifecycle.LiveData |
|||
import androidx.lifecycle.Observer |
|||
import java.util.concurrent.CountDownLatch |
|||
import java.util.concurrent.TimeUnit |
|||
import java.util.concurrent.TimeoutException |
|||
|
|||
@VisibleForTesting(otherwise = VisibleForTesting.NONE) |
|||
fun <T> LiveData<T>.getOrAwaitValue( |
|||
time: Long = 2, |
|||
timeUnit: TimeUnit = TimeUnit.SECONDS, |
|||
afterObserve: () -> Unit = {} |
|||
): T { |
|||
var data: T? = null |
|||
val latch = CountDownLatch(1) |
|||
val observer = object : Observer<T> { |
|||
override fun onChanged(o: T?) { |
|||
data = o |
|||
latch.countDown() |
|||
this@getOrAwaitValue.removeObserver(this) |
|||
} |
|||
} |
|||
this.observeForever(observer) |
|||
|
|||
try { |
|||
afterObserve.invoke() |
|||
|
|||
// Don't wait indefinitely if the LiveData is not set. |
|||
if (!latch.await(time, timeUnit)) { |
|||
throw TimeoutException("LiveData value was never set.") |
|||
} |
|||
|
|||
} finally { |
|||
this.removeObserver(observer) |
|||
} |
|||
|
|||
@Suppress("UNCHECKED_CAST") |
|||
return data as T |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue