<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by nddquang on Medium]]></title>
        <description><![CDATA[Stories by nddquang on Medium]]></description>
        <link>https://medium.com/@ngodinhduyquang?source=rss-f6cf1b6c0495------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*j2I3LT7u0BeVvTD_xe3esg.gif</url>
            <title>Stories by nddquang on Medium</title>
            <link>https://medium.com/@ngodinhduyquang?source=rss-f6cf1b6c0495------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:57:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ngodinhduyquang/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Coroutines Flow vs Suspend Function, Sequence and livedata]]></title>
            <link>https://ngodinhduyquang.medium.com/coroutines-flow-vs-suspend-function-sequence-and-livedata-108a8dc72787?source=rss-f6cf1b6c0495------2</link>
            <guid isPermaLink="false">https://medium.com/p/108a8dc72787</guid>
            <dc:creator><![CDATA[nddquang]]></dc:creator>
            <pubDate>Sat, 26 Sep 2020 04:43:04 GMT</pubDate>
            <atom:updated>2020-09-26T04:43:04.066Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I will make a brief compare between Flows with other way to return data when we deal with coroutines such as: <strong>suspend fun</strong>, <strong>sequence</strong> and <strong>livedata.</strong></p><p>When using suspend function in Coroutines, most of the time it allows us return only one time:</p><pre>suspend fun demoSuspendFun(): List&lt;Int&gt; {<br>    delay(1000)<br>    return listOf(1, 2, 3, 4, 5, 6)<br>}</pre><p>This way is okay if we want to all data return at once. What if we have three functions, each of function return 2 items after delay 1 second:</p><pre>suspend fun longTask1(): List&lt;Int&gt; {<br>    delay(1000)<br>    return listOf(1, 2)<br>}<br><br>suspend fun longTask2(): List&lt;Int&gt; {<br>    delay(1000)<br>    return listOf(3, 4)<br>}<br><br>suspend fun longTask3(): List&lt;Int&gt; {<br>    delay(1000)<br>    return listOf(5, 6)<br>}</pre><p>With suspend function, we have to implement like this:</p><pre>suspend fun demoSuspendFun(): List&lt;Int&gt; {<br>    val result = mutableListOf&lt;Int&gt;()<br>    result.addAll(longTask1())<br>    result.addAll(longTask2())<br>    result.addAll(longTask3())<br>    return result<br>}</pre><p>With this implement, we have to wait for about 3 seconds before processing all 6 items. We can check this by running this:</p><pre>fun main() = runBlocking {<br>    val startTime = System.currentTimeMillis()<br><br>    demoSuspendFun().forEach {<br>        println(&quot;receive $it after ${System.currentTimeMillis() - startTime}ms&quot;)<br>    }<br>}</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*lmY-oV_Jy8a6GKoxqat1uw.png" /></figure><p>I wonder if we have other ways to handle every 2 items when they become available?</p><p>Just escape from coroutine a little bit. In Kotlin, if our tasks are synchronous tasks, we can use Sequence. This way we can process each task:</p><pre>fun longSyncTask1(): List&lt;Int&gt; {<br>    Thread.sleep(1000)<br>    return listOf(1, 2)<br>}<br><br>fun longSyncTask2(): List&lt;Int&gt; {<br>    Thread.sleep(1000)<br>    return listOf(3, 4)<br>}<br><br>fun longSyncTask3(): List&lt;Int&gt; {<br>    Thread.sleep(1000)<br>    return listOf(5, 6)<br>}</pre><pre>fun demoSequence() = sequence {<br>    yield(longSyncTask1())<br>    yield(longSyncTask2())<br>    yield(longSyncTask3())<br>}</pre><p>Let’s check if it works as we expected. First we write a main function for this case:</p><pre>demoSequence().forEach {<br>    println(&quot;receive $it after ${System.currentTimeMillis() - startTime}ms&quot;)<br>}</pre><p>This time, we receive every 2 items after 1 second:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*JYbAcopTVDtDvA2Lv7sESA.png" /></figure><p>Now if we try to call suspend fun inside Sequence, it raises warning because Sequence not support that. We have to use Flow instead:</p><pre>fun demoFlow() = flow {<br>    emit(longTask1())<br>    emit(longTask2())<br>    emit(longTask3())<br>}</pre><p>Then we check result by this code:</p><pre>demoFlow().collect {<br>    println(&quot;receive $it after ${System.currentTimeMillis() - startTime}ms&quot;)<br>}</pre><p>We get the same result as Sequence. The different is that in this case, we handle with suspend functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*irdDMkkF_r2Swgv7_PKAGA.png" /></figure><h4>Flow with Livedata</h4><p>Sometimes, we want our function return to livedata to make it easy for observering from UI layer, we do something like this:</p><pre>fun getIntList() = liveData { <br>    emit(listOf(1, 2, 3))<br>}</pre><p>It’s okay but if we already have flow, we can use the extension “.asLiveData()” to make the same. It helps us to reduce poilerplate code.</p><p>To explain why it helps us to reduce the complexity. Livedata has “.<strong>switchMap</strong>” to transform from livedata to another livedata, like this:</p><pre>fun fetchWeather(): <em>LiveData</em>&lt;Int&gt; {<br>    ...<br>}<br><br>val currentWeatherLiveData: <em>LiveData</em>&lt;String&gt; =<br>    fetchWeatherFlow()<br>        .switchMap {<br>            liveData { <br>                emit(heavyTransformation(it)) <br>            } <br>        }</pre><p>Using switchMap, it requires many code level. It will make it hard to debug . Using Flow, we can make the above become more simple like this:</p><pre>fun fetchWeatherFlow() = flow&lt;Int&gt; {<br><br>}<br><br>val currentWeatherLiveData: <em>LiveData</em>&lt;String&gt; =<br>    fetchWeatherFlow()<br>        .map { heavyTransformation(it) }<br>        .asLiveData()</pre><p>That’s why in Repository or Datasource, it’s better to use Flow instead of LiveData.</p><h4>Preferences</h4><ul><li><a href="https://medium.com/androiddevelopers/livedata-with-coroutines-and-flow-part-iii-livedata-and-coroutines-patterns-592485a4a85a">LiveData with Coroutines and Flow — Part III: LiveData and coroutines patterns</a></li><li><a href="https://kotlinlang.org/docs/reference/coroutines/flow.html">Asynchronous Flow</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=108a8dc72787" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple video player with Brightcove and ExoPlayer 2 (Part 2)]]></title>
            <link>https://ngodinhduyquang.medium.com/simple-video-player-with-brightcove-and-exoplayer-2-part-2-dfde1318216d?source=rss-f6cf1b6c0495------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfde1318216d</guid>
            <dc:creator><![CDATA[nddquang]]></dc:creator>
            <pubDate>Sat, 26 Sep 2020 03:11:21 GMT</pubDate>
            <atom:updated>2020-09-26T03:11:21.433Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous blog, we’ve created a simple demo that play video taken from Brightcove. Now in this part, we will try to:</p><ol><li>Load a playlist</li><li>Apply adaptive streaming</li><li>Show subtitles</li></ol><h3>Load playlist from Brightcove</h3><p>Just like getting video, we need Brightcove’s <strong>Catalog </strong>object to get playlist by its ID. Call the function <strong>findPlaylistByID:</strong></p><pre>catalog.findPlaylistByID(playlistId, object : PlaylistListener() {<br>    override fun onPlaylist(p0: Playlist?) {<br>        val mediaItems = mutableListOf&lt;MediaItem&gt;()<br>        p0?.<em>videos</em>?.forEach { video -&gt;<br>            val source = ExoPlayerSourceSelector().selectSource(video)<br>            val mediaItem = buildMediaItem(source)<br>            mediaItems.add(it)<br>        }<br>        player.addMediaItems(mediaItems)<br>    }<br>})</pre><p>Method <strong>onPlaylist </strong>of the PlaylistListener receives an input of <strong>Playlist</strong> type with hold a list of videos, so we will use this video list to create a mediaItem list and add them to our player with this command:</p><pre>player.addMediaItems(mediaItems)</pre><p>Now our player will hold a playlist, we can use action Next/Back to play other videos.</p><h3>Apply adaptive streaming</h3><p><strong>Adaptive Streaming</strong> is a technique for streaming media that the quality of stream can vary according to the network bandwidth. That means users can experience the best-quality media that their bandwidth allows.</p><p>The media content is split into multiple tracks with different qualities (bit rates and resolutions). The player will select a track based on the available network bandwidth.</p><p>Each track is split into chunks of a given duration (2–10 seconds). If the available bandwidth changes, player will switch to different tracks. This is applied by default to Exoplayer. However, we can indicate the maximum quality to be fetched. We can do that by adding property to the DefaultTrackSelector like this:</p><pre>private fun initPlayer(): Player {<br>    val trackSelector = DefaultTrackSelector(context).apply {<br>        setParameters(<br>            buildUponParameters().setMaxVideoSizeSd()<br>        )<br>    }<br><br>    return SimpleExoPlayer.Builder(context)<br>        .setTrackSelector(trackSelector)<br>        .build()<br>}</pre><p>We try to set the maximum quality to be SD to see if this adaptive streaming works. The SD quality normally maximum video size width 1279 and height 719. You can set other quality’s max size if you want.</p><h3>Show Subtitles</h3><p>Now with subtitles you want to show along with your video. Exoplayer 2 provides us to add an array of subtitles. The question is how to get subtitles from <strong>Brightcove</strong>?</p><p>After getting video/playlist from Brightcove, in Video object we will have a map <strong>properties </strong>with a key named <strong>“captionSources”. </strong>Subtitles will be placed there if any.</p><p>So we build our mediaItem like this:</p><pre>val mediaItem = MediaItem.Builder()<br>    .setUri(source.url)<br>    .setDrmUuid(C.WIDEVINE_UUID)<br>    .setDrmMultiSession(true)<br><br>val captionSources = video.properties[Video.Fields.CAPTION_SOURCES] as List&lt;Pair&lt;<em>Uri</em>, <em>BrightcoveCaptionFormat</em>&gt;&gt;<br>if (captionSources.isNotEmpty()) {<br>    val captions = mutableListOf&lt;MediaItem.Subtitle&gt;()<br>    captionSources.forEach {<br>        val subtitle = MediaItem.Subtitle(<br>            it.first,<br>            MimeTypes.TEXT_VTT,  // The correct MIME type.<br>            it.second.language(),<br>            SELECTION_FLAG_DEFAULT<br>        )<br><br>        captions.add(subtitle)<br>    }<br><br>    mediaItem.setSubtitles(captions)<br>}<br><br>if (source.hasKeySystem(Source.Fields.WIDEVINE_KEY_SYSTEM)) {<br>    mediaItem.setDrmLicenseUri(source.getLicenseUrl())<br>}<br><br>mediaItem.build()</pre><h3>Preferences</h3><p><a href="https://codelabs.developers.google.com/codelabs/exoplayer-intro/#0">Media streaming with ExoPlayer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfde1318216d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Testing Scenarios]]></title>
            <link>https://ngodinhduyquang.medium.com/android-testing-case-by-case-bcd79593849c?source=rss-f6cf1b6c0495------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd79593849c</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dagger-2-test]]></category>
            <dc:creator><![CDATA[nddquang]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 15:57:38 GMT</pubDate>
            <atom:updated>2021-07-15T15:33:43.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*bZcuMBJFdveXY5vbMfFJkg.png" /></figure><p><strong><em>Table of contents</em></strong></p><p><strong>· </strong><a href="#22bf"><strong>Best practices</strong></a><strong><br>· </strong><a href="#6e53"><strong>Some scenarios for writing test cases</strong></a><strong><br> ∘ </strong><a href="#f299"><strong>Simple unit test for class</strong></a><strong><br> ∘ </strong><a href="#af01"><strong>Testing callback function using Concurrent Unit</strong></a><strong><br> ∘ </strong><a href="#b1a4"><strong>Testing callback function using own class</strong></a><strong><br> ∘ </strong><a href="#3353"><strong>Testing suspend function</strong></a><strong><br> ∘ </strong><a href="#34b8"><strong>Testing coroutine when launch in Dispatchers.Main</strong></a><strong><br> ∘ </strong><a href="#5610"><strong>Testing Dagger (Replace module)</strong></a><strong><br> ∘ </strong><a href="#0e3b"><strong>Testing with mockwebserver</strong></a><strong><br> ∘ </strong><a href="#4928"><strong>Unit Test that need Application/Activity</strong></a><strong><br> ∘ </strong><a href="#e9f5"><strong>Provide Testing Application</strong></a><strong><br> ∘ </strong><a href="#0565"><strong>Test with Room</strong></a><strong><br>· </strong><a href="#42db"><strong>Preferences</strong></a></p><h3>Best practices</h3><ul><li>Test case should have 3 separated parts: <strong>GIVEN — WHEN — THEN</strong></li><li>Use prefix <strong>actual_ </strong>and<strong> expected_</strong> for 2 comparable params in assert</li><li>Should hardcode input to make test case understandable</li><li>Should not make a big test case with many assert → Separate to some small test cases with specific purpose</li><li>Don’t make test case extends from each other. Instead we should make component and make it run before test</li><li>Test case should not include logic. Make it as simple as possible</li><li>Focus on integration test instead of mock-based tests</li><li>Should mock value that may change every time test run (such as Time)</li></ul><h3>Some scenarios for writing test cases</h3><h4>Simple unit test for class</h4><p>If class has no dependencies so testing is just simple. For example, we want to test function parseDate function of DateUtils class, just create this class, call function and assert the result.</p><pre>@Test<br><strong>public void </strong>parseDate_dateWrongFormat_returnNull() {<br>    Date expectedDate = DateUtils().parseDate(&quot;10/13/98&quot;, &quot;MM-dd-yy&quot;);<br>    assertNull(expectedDate);<br>}</pre><h4>Testing callback function using Concurrent Unit</h4><p>For testing async function that uses callback, we can use <a href="https://github.com/jhalterman/concurrentunit"><strong>concurrentunit</strong></a><strong> </strong>to pause thread to wait for callback is called.</p><p>First add library:</p><pre>testImplementation &#39;net.jodah:concurrentunit:0.4.6&#39;</pre><p>Use <strong>Waiter</strong> class to block and resume the main test thread, like this:</p><pre>@Test<br>public void shouldDeliverMessage() throws Throwable {<br>  final Waiter waiter = new Waiter();<br><br>  messageBus.registerHandler(message -&gt; {<br>    // Called on separate thread<br>    waiter.assertEquals(message, &quot;foo&quot;);<br>    waiter.resume();<br>  };<br>  <br>  // Wait for resume() to be called<br>  waiter.await(1000);<br>}</pre><h4>Testing callback function using own class</h4><p>If you don’t want to use library for async function, try to write your own Waiter class with the same idea:</p><pre>class Await {<br>    private val latch = CountDownLatch(1)<br><br>    fun resume() {<br>        latch.countDown()<br>    }<br><br>    fun assertEquals(expected: Any?, actual: Any?) {<br>        if (expected == null &amp;&amp; actual == null) return<br>        if (expected != null &amp;&amp; expected == actual) return<br><br>        latch.countDown()<br>        throw AssertionError(&quot;expected:&lt;\&quot;$expected\&quot;&gt; but was:&lt;\&quot;$actual\&quot;&gt;&quot;)<br>    }<br><br>    fun await(<br>        time: Long = 2,<br>        timeUnit: TimeUnit = TimeUnit.SECONDS<br>    ) {<br>        if (!latch.await(time, timeUnit))<br>            throw TimeoutException(&quot;Test timed out while waiting for an expected result&quot;)<br>    }<br><br>}</pre><h4><strong>Testing suspend function</strong></h4><p>First, add the librarykotlinx-coroutines-test</p><pre>testImplementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion&quot;</pre><p>Write test case with <strong>runBlockingTest</strong> to call suspend function</p><pre><strong>class </strong>Repository() {<br>    <strong>suspend fun </strong>getData(): String {<br>        delay(1000)<br>        <strong>return </strong>&quot;Result&quot;<br>    }<br>}</pre><pre>@Test<br><strong>fun </strong>testFunction() = <em>runBlockingTest </em><strong>{<br>    </strong>// Suspend function calling here<br>    <strong>val </strong>expectedResult = Repository().getData()<br><br>    // Assert<br>    assertTrue(&quot;Result&quot;, expectedResult)<br><strong>}</strong></pre><p>Sometimes, it raises error “This job has not completed yet”. Add this to test class:</p><pre>@get:Rule<br><strong>var </strong>instantExecutorRule = InstantTaskExecutorRule()</pre><h4>Testing coroutine when launch in Dispatchers.Main</h4><p>Check this code:</p><pre><strong>class </strong>ArticleViewModel : ViewModel() {<br>    <strong>private var </strong>likeCount = 0<br><br>    <strong>fun </strong>getLikeCount() = likeCount<br><br>    <strong>fun </strong>addLikeCount() {<br>        <em>viewModelScope</em>.<em>launch </em><strong>{<br>            </strong>likeCount += 1<br>            likeCount<br>        <strong>}<br>    </strong>}<br>}<br><br><strong>class </strong>ArticleViewModelTest {<br>    @Test<br>    <strong>fun </strong>addLikeCount() = <em>runBlocking </em><strong>{<br>        val </strong>articleViewModel = ArticleViewModel()<br>        articleViewModel.addLikeCount()<br>        Assert.assertEquals(1, articleViewModel.getLikeCount())<br>    <strong>}<br></strong>}</pre><p>If we have test case for coroutine code that is launched in Dispatchers.Main. The test will fail because the Dispatchers.Main uses Android main looper which is not available during unit tests. That’s available in instrumentation tests but not in unit tests.</p><p>We have to fix this by replacing the Dispatchers with a TestCoroutineDispatcher. Like this:</p><pre>@ExperimentalCoroutinesApi<br><strong>class </strong>ArticleViewModelTest {<br>    <strong>private val </strong>testDispatcher = TestCoroutineDispatcher()<br><br>    @Before<br>    <strong>fun </strong>setup() {<br>        Dispatchers.setMain(testDispatcher)<br>    }<br><br>    @After<br>    <strong>fun </strong>tearDown() {<br>        Dispatchers.resetMain()<br>        testDispatcher.cleanupTestCoroutines()<br>    }<br><br>    @Test<br>    <strong>fun </strong>addLikeCount() = <em>runBlocking </em><strong>{<br>        val </strong>articleViewModel = ArticleViewModel()<br>        articleViewModel.addLikeCount()<br>        Assert.assertEquals(1, articleViewModel.getLikeCount())<br>    <strong>}<br></strong>}</pre><h4>Testing Dagger (Replace module)</h4><p>If you provide dependencies via dagger and then in test class, you want to provide with mock value. Do the following:</p><ol><li><strong>dagger-compiler</strong> need to be included in test:<br><strong>kaptTest &quot;com.google.dagger:dagger-compiler:$dagger2_version&quot;</strong></li><li>Create test module in test’s source set:</li></ol><pre>@Module<br><strong>object </strong>TestConstantModule {<br>    @Provides<br>    @Named(<em>ENDPOINT</em>)<br>    <strong>fun </strong>provideEndpoint(): String {<br>        <strong>return </strong>&quot;http://127.0.0.1:8080&quot;<br>    }<br>}</pre><p>3. Create test component in test’s source set, using the test module. We can implement the app component to use it’s methods:</p><pre>@Singleton<br>@Component(modules = [TestConstantModule::<strong>class</strong>])<br><strong>interface </strong>TestAppComponent: AppComponent {<br>    @Component.Builder<br>    <strong>interface </strong>Builder {<br>        <strong>fun </strong>build(): TestAppComponent<br>    }<br>}</pre><p>4. Then we can use test component in test classes:</p><pre>DaggerTestAppComponent.builder().build()</pre><h4>Testing with mockwebserver</h4><p>We use <a href="https://github.com/square/okhttp/tree/master/mockwebserver">mockwebserver</a> to run server on local machine instead of calling the real API. Here step to do it:</p><ol><li>Add mockwebserver to project</li></ol><pre>testImplementation(&quot;com.squareup.okhttp3:mockwebserver:$mockwebserverVersion&quot;)</pre><p>2. In test class, we start webserver in @Before and shutdown in @After:</p><pre>@Before<br><strong>fun </strong>setup() {<br>    <em>mockWebServer </em>= MockWebServer()<br>}<br><br>@After<br><strong>fun </strong>teardown() {<br>    <em>mockWebServer</em>.shutdown()<br>}</pre><p>3. If you use <strong>Retrofit</strong>, create it using this:</p><pre>val retrofit = Retrofit.Builder()<br>    .baseUrl(mockWebServer.url(https://medium.com/&quot;/&quot;))<br>    .build()</pre><p>4. In test function, we write scenario for this mockWebServer:</p><pre>@ExperimentalCoroutinesApi<br>@Test<br><strong>fun </strong>successResponseMockWebServer() {<br>    mockWebServer.dispatcher = <strong>object </strong>: Dispatcher() {<br>        <strong>override fun </strong>dispatch(request: RecordedRequest): MockResponse {<br>            <strong>return </strong>MockResponse().setResponseCode(200)<br>                .setBody(MockResponseFileReader.response(&quot;success.json&quot;))<br>        }<br>    }<br><br>    <strong>.....</strong><br>}</pre><p>Now our code will call to local server then return response as we set.</p><p>File “success.json” should be placed in s<strong>rc/test/resources. </strong>The code for<strong> </strong>MockResponseFileReader is below:</p><pre><strong>object </strong>MockResponseFileReader {<br><br>    <strong>fun </strong>response(path: String): String {<br>        <strong>val </strong>reader = InputStreamReader(<strong>this</strong>.<em>javaClass</em>.<em>classLoader</em>!!.getResourceAsStream(path))<br>        <strong>val </strong>content = reader.<em>readText</em>()<br>        reader.close()<br><br>        <strong>return </strong>content<br>    }<br><br>}</pre><h4>Unit Test that need Application/Activity</h4><p>AndroidX Test is a collection of libraries for testing. It includes classes and methods that give you versions of components like Applications and Activities. We need these dependencies in gradle:</p><pre><em>// AndroidX Test - JVM testing</em><br>testImplementation &quot;androidx.test.ext:junit-ktx:$androidXTestExtKotlinRunnerVersion&quot;<br><br>testImplementation &quot;androidx.test:core-ktx:$androidXTestCoreVersion&quot;<br><br>testImplementation &quot;org.robolectric:robolectric:$robolectricVersion&quot;</pre><p>Add JUnit Test Runner, add @RunWith(AndroidJUnit4::class) provided by androidx.test.ext:junitabove your test class. Then when need components, call the appropriate method, such as:</p><pre>ApplicationProvider.getApplicationContext()</pre><p>**The above code can run because of the androidx.test:core</p><p>One of the benefits of the AndroidX Test APIs is that they are built to work both for local tests and instrumented tests. <strong>Roboelectric </strong>will help to provide<strong> </strong>simulated Android environment.</p><h4>Provide Testing Application</h4><p>Sometimes you want to replace the real Application with your testing Application. You can do it with robolectric by flowing these steps:</p><ol><li>Create Test Application class</li><li>Create file robolectric.properties with this line of code:application=com.example.TestApplication</li></ol><h4><strong>Test with Room</strong></h4><p>While testing with room, we must run under a registering instrumentation. So add@RunWith(AndroidJUnit4::class) above your test class.</p><p>Create an in-memory database using <a href="https://developer.android.com/reference/androidx/room/Room.html#inMemoryDatabaseBuilder(android.content.Context,%20java.lang.Class%3CT%3E)">Room.inMemoryDatabaseBuilder.</a> Normal databases are meant to persist. By comparison, an in-memory database will be completely deleted once the process that created it is killed, since it&#39;s never actually stored on disk. Always use and in-memory database for your tests.</p><pre>@Before<br>fun initDb() {<br>    <em>// Using an in-memory database so that the information stored here disappears when the</em><br>    <em>// process is killed.</em><br>    database = Room.inMemoryDatabaseBuilder(<br>        getApplicationContext(),<br>        ToDoDatabase::class.java<br>    ).allowMainThreadQueries().build()<br>}</pre><pre>@After<br>fun cleanUp() {<br>    database.close()<br>}</pre><p>We use <strong>.allowMainThreadQueries() </strong>to allow DAO run on main thread. Without that, we have to run it on different thread, that’s make our test case more complex. As we test the login only, not the UI, so just allow it to run on Main Thread.</p><p>In test case, just get the DAO from our test database and write test case for it. Normally, we try to <strong>insert some mock entities</strong> to database and then <strong>getEntity</strong> to verify data available in database.</p><pre><em>// runBlocking is used here because of https://github.com/Kotlin/kotlinx.coroutines/issues/1204</em><br><em>// TODO: Replace with runBlockingTest once issue is resolved</em><br>@Test<br>fun saveTask_retrievesTask() = runBlocking {<br>    <em>// GIVEN - A new task saved in the database.</em><br>    val newTask = Task(&quot;title&quot;, &quot;description&quot;, false)<br>    localDataSource.saveTask(newTask)<br><br>    <em>// WHEN  - Task retrieved by ID.</em><br>    val result = localDataSource.getTask(newTask.id)<br><br>    <em>// THEN - Same task is returned.</em><br>    assertThat(result.succeeded, `is`(true))<br>    result as Success<br>    assertThat(result.data.title, `is`(&quot;title&quot;))<br>    assertThat(result.data.description, `is`(&quot;description&quot;))<br>    assertThat(result.data.isCompleted, `is`(false))<br>}</pre><h3>Preferences</h3><p><a href="https://developer.android.com/training/testing/fundamentals">https://developer.android.com/training/testing/fundamentals</a></p><p><a href="https://phauer.com/2019/modern-best-practices-testing-java/">https://phauer.com/2019/modern-best-practices-testing-java/</a></p><p><a href="https://testing.googleblog.com/">https://testing.googleblog.com/</a></p><p><a href="https://github.com/square/okhttp/tree/master/mockwebserver">https://github.com/square/okhttp/tree/master/mockwebserver</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd79593849c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple video player with Brightcove and ExoPlayer 2]]></title>
            <link>https://ngodinhduyquang.medium.com/simple-video-player-with-brightcove-and-exoplayer-2-b8a15767a8ba?source=rss-f6cf1b6c0495------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8a15767a8ba</guid>
            <category><![CDATA[brightcove]]></category>
            <category><![CDATA[exoplayer]]></category>
            <dc:creator><![CDATA[nddquang]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 05:54:20 GMT</pubDate>
            <atom:updated>2020-10-08T09:23:54.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*-GSA0mqsJsyoPeMIU5NRPA.png" /></figure><p><strong>Brightcove</strong> Video Cloud is the leading online video hosting platform and online video player solution. It supports protection of our videos, apply analytics or even monetize video across multiple devices.</p><p>In the field of Android developing, we want to make it simple and fast as much as possible. To support that, <strong>Brightcove</strong> has integrated with the powerful <strong>ExoPlayer 2</strong> from Google. In this blog, I will make a simple demo Android App using <strong>Brightcove</strong> with <strong>ExoPlayer 2</strong>.</p><h3>Table of contents</h3><p><strong><em>· </em></strong><a href="#da1d"><strong><em>Table of contents</em></strong></a><strong><em><br>· </em></strong><a href="#450f"><strong><em>Modify project to use Brightcove Player SDK</em></strong></a><strong><em><br> ∘ </em></strong><a href="#eba4"><strong><em>Set compile with Java 8</em></strong></a><strong><em><br> ∘ </em></strong><a href="#23bd"><strong><em>Add Brightcove’s maven repo</em></strong></a><strong><em><br> ∘ </em></strong><a href="#cb1b"><strong><em>Add dependencies</em></strong></a><strong><em><br>· </em></strong><a href="#0888"><strong><em>Code the application</em></strong></a><strong><em><br> ∘ </em></strong><a href="#ccec"><strong><em>Allow app to use Internet</em></strong></a><strong><em><br> ∘ </em></strong><a href="#9c97"><strong><em>Making UI with ExoPlayer</em></strong></a><strong><em><br> ∘ </em></strong><a href="#51f6"><strong><em>Get video source from Brightcove</em></strong></a><strong><em><br> ∘ </em></strong><a href="#0908"><strong><em>Play single video</em></strong></a><strong><em><br> ∘ </em></strong><a href="#1489"><strong><em>Play DRM protected content</em></strong></a><strong><em><br>· </em></strong><a href="#3af4"><strong><em>References</em></strong></a></p><h3>Modify project to use Brightcove Player SDK</h3><h4>Set compile with Java 8</h4><p>For ExoPlayer v2.9.0+, you need to enable Java 8 support. To do this, add the following to the android section of your app&#39;s <strong>build.gradle</strong> file:</p><pre>compileOptions <strong>{<br>    </strong>targetCompatibility JavaVersion.<em>VERSION_1_8<br></em><strong>}</strong></pre><h4>Add Brightcove’s maven repo</h4><p>Add Brightcove’s maven repo in repositories section, can set it the whole project or just needed module:</p><pre>maven <strong>{ </strong>url &#39;https://repo.brightcove.com/releases&#39; <strong>}</strong></pre><h4>Add dependencies</h4><p>In the dependencies section, we implement two libraries in our project, paste this in app’s <strong>build.gradle</strong>:</p><pre>implementation &quot;com.brightcove.player:android-sdk:6.10.0&quot;<br>implementation &quot;com.brightcove.player:exoplayer2:6.10.0&quot;</pre><pre>implementation &#39;com.google.android.exoplayer:exoplayer:2.12.0&#39;</pre><p>Remember to sync project for all these changes applied!!!</p><h3>Code the application</h3><h4>Allow app to use Internet</h4><p>Open the AndroidManifest.xml file and insert the following to enable Internet access.</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</pre><h4>Making UI with ExoPlayer</h4><p>To make our demo simple, we will use MainActivity as the video player. So, we need a player view inside activity_main.xml. As I have mentioned above, Brightcove has integration with ExoPlayer 2. Brightcove has already created a player view based on ExoPlayer called <strong>BrightcoveExoPlayerVideoView</strong>. We can use that in our project to make everything simple. However, for this demo, I want make it differently, so I will use directly Google’s ExoPlayer 2 to implement the player view. Because player view is only the easy one, we can re-use that in other projects that not depend on Brightcove.</p><p>To create layout for media player, we need a <strong>PlayerView</strong> from <strong>ExoPlayer</strong>.</p><pre>&lt;com.google.android.exoplayer2.ui.PlayerView<br>    android:id=&quot;@+id/exoPlayerView&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>    app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>    app:show_buffering=&quot;when_playing&quot;<br>    /&gt;</pre><h4>Get video source from Brightcove</h4><p>To get video source from Brightcove, we need 3 information: <strong>AccountID</strong>, <strong>PolicyKey</strong> and <strong>VideoId.</strong> I will show you how to get all these information in Brightcove’s video cloud:</p><ol><li><strong>Account ID</strong>: hover in <strong>Admin </strong>menu, then select <strong>Account Information</strong>, you will find Account ID there.</li></ol><p><strong>2. Policy Key</strong>: open the <strong>Players </strong>menu and either create a new player or locate the player to which you wish to add the plugin. Then select player to open the player’s details. In the left navigation menu, select <strong>JSON Editor</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*7rZyNmJxlCXW-b9A.png" /></figure><p>In the displayed JSON code, you will see the policy key:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*z_dC2zfNhqFMpbtb.png" /><figcaption>JSON Editor (Source: <a href="https://apis.support.brightcove.com/">https://apis.support.brightcove.com/</a>)</figcaption></figure><p>3. <strong>Video Id</strong>: open <strong>Media</strong> menu, this page will list out all videos and playlists. It’s easy to find a videoId here.</p><h4>Play single video</h4><p>Now with 3 info we’ve got, let’s play this video. First, we need to create catalog using <strong>BrightcoveSDK, </strong>then use it to find video from id:</p><pre>val catalog = Catalog(<br>    EventEmitterImpl(),<br>    YOUR_ACCOUNT_ID,<br>    YOUR_POLICY_KEY<br>)</pre><pre>catalog.findVideoByID(getString(R.string.<em>videoId</em>), object: VideoListener() {<br>    override fun onVideo(p0: Video?) {<br>        p0?.<em>let </em><strong>{ </strong>video <strong>-&gt; </strong>playVideo(video) <strong>}<br>    </strong>}<br>})</pre><p>Play video could be made as simple as this:</p><pre>private<strong> </strong>fun<strong> </strong>playVideo(video: Video) {<br>    val<strong> </strong>source = ExoPlayerSourceSelector().selectSource(video)<br>    val<strong> </strong>mediaItem = buildMediaItem(source)<br><br>    val<strong> </strong>player = SimpleExoPlayer.Builder(context).build()<br>    player.addMediaItem(mediaItem)<br>    player.prepare()<br>    videoView.<em>player </em>= player<br>}</pre><p>The <strong><em>buildMediaItem</em></strong> function:</p><pre><strong>private fun </strong>buildMediaItem(video: Video, source: Source): MediaItem {<br>    <strong>val </strong>mediaItem = MediaItem.Builder()<br>        .setUri(source.<em>url</em>)<br><br>    <strong>return </strong>mediaItem.build()<br>}</pre><p>After using catalog to get video based on videoID, we use the video to create mediaItem. After that, this MediaItem is added to our player. We just add this player to our ExoPlayer’s playerView we created in the first step then the video is played properly.</p><blockquote><strong>Attention 1</strong>: remember to release the player when it’s no longer needed, so as to free up limited resources such as video decoders for use by other applications. This can be done by calling player.release()</blockquote><blockquote><strong>Attention 2: </strong>sometimes video played but no image and no sound. It’s because the playback is DRM protected. Source from Brightcove not yet support video only or audio only, so if we just have black screen. In order to play video in this case, we have to update our function <strong>buildMediaItem</strong>. Please check the next step.</blockquote><h4>Play DRM protected content</h4><p>In source object, we can see <strong>properties</strong> map with key “key_systems”, it contains info of some drm providers for this source such as <strong>Fairplay</strong> or <strong>Widevine</strong>. Now we create an kotlin extension to get LicenseURL from source:</p><pre><em>/**<br> * Extension function for getting License URL from source<br> */<br></em><strong>private fun </strong>Source.getLicenseUrl() = (<em>properties</em>[Source.Fields.<em>KEY_SYSTEMS</em>] <strong>as </strong>Map&lt;String, Map&lt;String, String&gt;&gt;).get(Source.Fields.<em>WIDEVINE_KEY_SYSTEM</em>)!!.get(Source.Fields.<em>LICENSE_URL</em>)</pre><p>Now for protected content, we edit our mediaItem like below:</p><pre><strong>private fun </strong>buildMediaItem(video: Video, source: Source): MediaItem {<br>    <strong>val </strong>mediaItem = MediaItem.Builder()<br>        .setUri(source.<em>url</em>)<br>        .setDrmUuid(C.<em>WIDEVINE_UUID</em>)<br>        .setDrmMultiSession(<strong>true</strong>)<br><br>    <strong>if </strong>(source.hasKeySystem(Source.Fields.<em>WIDEVINE_KEY_SYSTEM</em>)) {<br>        mediaItem.setDrmLicenseUri(source.<em>getLicenseUrl</em>())<br>    }<br><br>    <strong>return </strong>mediaItem.build()<br>}</pre><p>Finally, for better view, set activity’s orientation as horizontal because we’re making the video, aren’t we :)</p><p>Run the app, our demo will look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*FNkQM36C0cSfCLCe" /></figure><p>Next blogs, we will load playlist and apply track selection. See next part here:</p><p><a href="https://medium.com/@ngodinhduyquang/simple-video-player-with-brightcove-and-exoplayer-2-part-2-dfde1318216d">https://medium.com/@ngodinhduyquang/simple-video-player-with-brightcove-and-exoplayer-2-part-2-dfde1318216d</a></p><h3>References</h3><ul><li><a href="https://sdks.support.brightcove.com/android/basics/step-step-simple-video-app-using-native-sdk-android.html">Step-by-Step: Simple Video App using the Native SDK for Android</a></li><li><a href="https://exoplayer.dev/media-sources.html">Media sources</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8a15767a8ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>